Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close
Add dependency for itext library in your build.gradle.
1 |
compile 'com.itextpdf:itextpdf:5.0.6' |
Create file path to store the pdf file in your device.
1 2 3 4 |
String fpath = "/sdcard/" + fname + ".pdf"; File file = new File(fpath); if (!file.exists()) { file.createNewFile(); } |
Create your custom font for your pdf using FontFamily.
1 2 |
Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); |
Create an instance of document class.
1 2 3 4 |
Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(file.getAbsoluteFile())); document.open(); |
Add paragraph in your document using add method.
1 2 |
document.add(new Paragraph("My First Pdf !")); document.add(new Paragraph("Hello World")); |
Create the following class “MyPdf.java” . I assume that the code is pretty much self-explaining. I tried to add lots of comments to make it easier to understand.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class MyPdf { //write method takes two parameter pdf name and content //return true if pdf successfully created public Boolean write(String fname, String fcontent) { try { //Create file path for Pdf String fpath = "/sdcard/" + fname + ".pdf"; File file = new File(fpath); if (!file.exists()) { file.createNewFile(); } // To customise the text of the pdf // we can use FontFamily Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12); // create an instance of itext document Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(file.getAbsoluteFile())); document.open(); //using add method in document to insert a paragraph document.add(new Paragraph("My First Pdf !")); document.add(new Paragraph("Hello World")); // close document document.close(); return true; } catch (IOException e) { e.printStackTrace(); return false; } catch (DocumentException e) { e.printStackTrace(); return false; } }} |
Be the first to comment.