Exploring iText : To Create PDF in Android

iText — Best PDF Creator Library for Java & Android

Your developer journey with iText begins here

After a long time, today I worked on new library that is iText as I have to implement functionality to give reports in PDF format in my running application.

I googled a lot and after all I found best library to create PDF very easily using JAVA code (you can use for android too).

I would like to share it with you all so it may useful in future.

See What I have done:

Lets See How to do it?

First of all, you need to add dependency in build.gradle (you can find latest version of that library here):

compile 'com.itextpdf:itextg:5.5.10'

Now we will see step by step how to create whole PDF: [Focus on comment, that will explain you everything :)]

Creating Document object:

* Creating Document
Document document = new Document();
// Location to save
PdfWriter.getInstance(document, new FileOutputStream(dest));

// Open to write

Setting up Document:

// Document Settings
document.addAuthor("Android School");
document.addCreator("Pratik Butani");

Setting up Fonts from Assets:

* Variables for further use....
BaseColor mColorAccent = new BaseColor(0, 153, 204, 255);
float mHeadingFontSize = 20.0f;
float mValueFontSize = 26.0f;
* How to USE FONT....
BaseFont urName = BaseFont.createFont("assets/fonts/brandon_medium.otf", "UTF-8", BaseFont.EMBEDDED);

Creating Line Separator:

LineSeparator lineSeparator = new LineSeparator();
lineSeparator.setLineColor(new BaseColor(0, 0, 0, 68));

Adding Heading:

// Title Order Details...
// Adding Title....
Font mOrderDetailsTitleFont = new Font(urName, 36.0f, Font.NORMAL, BaseColor.BLACK);
// Creating Chunk
Chunk mOrderDetailsTitleChunk = new Chunk("Order Details", mOrderDetailsTitleFont);
// Creating Paragraph to add...
Paragraph mOrderDetailsTitleParagraph = new Paragraph(mOrderDetailsTitleChunk);
// Setting Alignment for Heading
// Finally Adding that Chunk

Adding Title - Value pair:

// Fields of Order Details...
// Adding Chunks for Title and value
Font mOrderIdFont = new Font(urName, mHeadingFontSize, Font.NORMAL, mColorAccent);
Chunk mOrderIdChunk = new Chunk("Order No:", mOrderIdFont);
Paragraph mOrderIdParagraph = new Paragraph(mOrderIdChunk);

Break line or add Line Separator:

document.add(new Paragraph(""));
document.add(new Chunk(lineSeparator));
document.add(new Paragraph(""));

Finally closing document:


Proguard Settings:

 -keep class javax.xml.crypto.dsig.** { *; }
-dontwarn javax.xml.crypto.dsig.**
-keep class javax.xml.crypto.** { *; }
-dontwarn javax.xml.crypto.**
 -keep class org.spongycastle.** { *; }
-dontwarn org.spongycastle.**

That’s all. :D :D

Its very easy and understandable to create quickly PDF document programmatically.

You can download demo: Android-PDF

Useful and Source Links:

Hope you will enjoy it. We will see more about iText in my Next Article.

Happy to see you. Dont forget to ❤ it.

Happy Coding :)