Exporting Data as PDF in Android. How to use the iText Android library | by Annas Surdyanto | Feb, 2022

How to use the iText Android library

Photo by CURVD® on Unsplash

One of the PDF libraries that is developer-friendly to implement is the iText library. To start using this library, we need to implement the iText dependency in our app Gradle.

implementation ("com.itextpdf:itextpdf:")
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

To start, let’s create a PDF service class so that our UI class is not contaminated with our PDF configuration. In this class, we can directly define our font style.

PDF Service Class Introduction
PDF File and Document Initialization

Writing a document is actually similar to typing directly into a Doc file in Microsoft Office. What makes it different is just we have no cursor and we need to control it programmatically.

document.add(Paragraph(" "))
private fun createParagraph(content: String): Paragraph{
val paragraph = Paragraph(content, BODY_FONT)
paragraph.firstLineIndent = 25f
paragraph.alignment = Element.ALIGN_JUSTIFIED
return paragraph
private fun createTable(column: Int, columnWidth: FloatArray): PdfPTable {
val table = PdfPTable(column)
table.widthPercentage = 100f
table.headerRows = 1
table.defaultCell.verticalAlignment = Element.ALIGN_CENTER
table.defaultCell.horizontalAlignment = Element.ALIGN_CENTER
return table
private fun createCell(content: String): PdfPCell {
val cell = PdfPCell(Phrase(content))
cell.horizontalAlignment = Element.ALIGN_CENTER
cell.verticalAlignment = Element.ALIGN_MIDDLE
//setup padding
cell.isUseAscender = true
cell.paddingLeft = 4f
cell.paddingRight = 4f
cell.paddingTop = 8f
cell.paddingBottom = 8f
return cell

We are going to have a paper consisting of two paragraphs and our user data having four variables (id, first name, middle name, last name).

data class User(
val id: Int,
val firstName: String,
val middleName: String,
val lastName: String
val userData = listOf(
User(1, "Amir", "Tan", "Khan"),
User(2, "Michael", "Calvin", "Gonzalez"),
User(3, "Alim", "Bin", "Hasan"),
User(4, "John", "Carl", "Tean"),
User(5, "James", "Brown", "Cold"),
User(6, "Virats", "Kader", "Can"),
User(7, "Lim", "Lui", "Pao"),
User(8, "Endro", "Tava", "Pero"),
User(9, "Dani", "Pedro", "Leo"),
User(10, "Leonardo", "Chris", "Luiza")
Create PDF Function Sample
Calling Create PDF Function in Activity
Result Preview

Exporting data into PDF is a cool feature that is actually simple to implement as long as we know the underlying concept of how an iText document adds an element.

Leave a Comment