Learn how to use the iText Android library
“I want this record in a PDF” — It’s a well-liked demand request by a number of Android customers.
Specifically circumstances, customers may need to have their knowledge printed out in PDF information. Knowledge reminiscent of cost proofs, transaction journals, historical past reviews, and so forth. This can be a easy want. Sadly, many android apps let this function stream away from their customers.
There are some the explanation why the PDF export function would not exist in apps. Certainly one of them is the complexity of its implementation — which is an assumption. Having a function that lets customers export their knowledge right into a PDF file is just not as complicated as fixing arithmetic issues. Let’s see tips on how to implement it in an Android utility.
One of many PDF libraries that’s developer-friendly to implement is the
iText library. To begin utilizing this library, we have to implement the iText dependency in our app Gradle.
As soon as it’s synced within the mission, we will go to the following step, organising our manifest. That is to let the app entry the telephone storage since we’re going to create a PDF file, and, in fact, put it aside within the telephone storage.
Add this code into the manifest.
Don’t overlook the legacy request to assist Android 11 and better.
We are actually executed having the
iText library in our mission. Simple? Wait, it’s not even the start of our PDF exporting methodology.
To begin, let’s create a PDF service class in order that our UI class is just not contaminated with our PDF configuration. On this class, we will straight outline our font fashion.
We simply have to set the font fashion by calling the
Font. That’s how we set the font fashion for use in our subsequent configuration.
We’ve additionally ready our pdf author specifically
path is the telephone storage listing the place the PDF file might be exported in. Now let’s check out the
if (!file.exists()) file.createNewFile()line features to create our PDF file.
Now now we have ready the storage listing and file. Nevertheless, the file now we have created remains to be a clean file. That is nothing to do with it on this step.
Now let’s dig deeper into doc initialization. To make a PDF file, we have to initialize
iText doc. This initialized variable will then act as our paper that we are going to write our knowledge on. The
doc = Doc() is the doc initialization.
doc.setPageSize is how we set margin and web page structure. We’ve had a doc with a clean web page now.
The doc creation doesn’t finish there. Since we’re about to make a PDF file, now we have to set the doc to be a PDF file by
pdf = PdfWriter.getInstance(doc,FileOutputStream(file)), and to scale back the reminiscence consumption of the file measurement, we compress the file as nicely by calling the
Simple. Let’s flip into the fundamental idea of writing the info into our doc.
To begin engaged on the doc, in fact, we have to open the doc. The code above has straight opened our doc by calling
Writing a doc is definitely much like typing straight right into a Doc file in Microsoft Workplace. What makes it totally different is simply now we have no cursor and we have to management it programmatically.
In different phrases, we have to guarantee that the ingredient we add to our doc is in the precise place. Under are the fundamental tips about tips on how to programmatically write our knowledge into the doc.
- So as to add an empty line, we will add a paragraph with an area string.
- To jot down a paragraph, we simply want to write down a paragraph content material contained in the paragraph bracket above
Paragraph("YOUR_PARAGRAPH"). Nevertheless, to keep away from creating paragraphs with the identical fashion repeatedly, we will create a paragraph inside a perform to be referred to as each time we’d like it.
personal enjoyable createParagraph(content material: String): Paragraph
val paragraph = Paragraph(content material, BODY_FONT)
paragraph.firstLineIndent = 25f
paragraph.alignment = Component.ALIGN_JUSTIFIED
- We will then simply create paragraphs by calling the
createParagraphperform to be added to our doc. Under is tips on how to use it.
- To make a desk, we have to outline a PDF desk. The next code reveals tips on how to make a desk:
personal enjoyable createTable(column: Int, columnWidth: FloatArray): PdfPTable
val desk = PdfPTable(column)
desk.widthPercentage = 100f
desk.headerRows = 1
desk.defaultCell.verticalAlignment = Component.ALIGN_CENTER
desk.defaultCell.horizontalAlignment = Component.ALIGN_CENTER
Within the code above, now we have a parameter named
column:Int which is the variety of columns. In addition to, we even have a
columnWidth that’s an array of float. This float array is the record of each single column of the desk created. Simple? yep, every part is clearly comprehensible.
Inside a desk, there have to be rows and columns. Any explicit space amongst them is known as a cell. Nevertheless, the rows should not outlined right here. It will likely be routinely generated by the cell we fill. Now let’s check out the following step for extra.
- The next code reveals tips on how to write inside a cell:
personal enjoyable createCell(content material: String): PdfPCell
val cell = PdfPCell(Phrase(content material))
cell.horizontalAlignment = Component.ALIGN_CENTER
cell.verticalAlignment = Component.ALIGN_MIDDLE
cell.isUseAscender = true
cell.paddingLeft = 4f
cell.paddingRight = 4f
cell.paddingTop = 8f
cell.paddingBottom = 8f
The primary level of the code above is that for every part we need to write in any explicit cell, we have to outline a PDF cell. The PDF cell performs as our cursor place. To keep away from repeatedly defining a cell, the perform above requires the cell content material purposing to straight put our content material contained in the cell.
Observe: If all columns in a row have been crammed by cells, the desk will generate a brand new row routinely once we add one other cell.
We’re going to have a paper consisting of two paragraphs and our person knowledge having 4 variables (id, first title, center title, final title).
The person knowledge class and its record are as follows:
knowledge class Consumer(
val id: Int,
val firstName: String,
val middleName: String,
val lastName: String
)val userData = listOf(
Consumer(1, "Amir", "Tan", "Khan"),
Consumer(2, "Michael", "Calvin", "Gonzalez"),
Consumer(3, "Alim", "Bin", "Hasan"),
Consumer(4, "John", "Carl", "Tean"),
Consumer(5, "James", "Brown", "Chilly"),
Consumer(6, "Virats", "Kader", "Can"),
Consumer(7, "Lim", "Lui", "Pao"),
Consumer(8, "Endro", "Tava", "Pero"),
Consumer(9, "Dani", "Pedro", "Leo"),
Consumer(10, "Leonardo", "Chris", "Luiza")
Now let’s make a perform to do the duties.
All executed, now we have configured all features wanted to export our person knowledge into PDF. Now let’s name this perform from our exercise, fragment, or composable context.
The pattern under reveals tips on how to name the perform from exercise:
All set. We’ve created the PDF export perform in our UI class and its consequence response as nicely. Nevertheless, in numerous circumstances, the response might differ relying on our wants.
On this pattern case, we let the app straight open the file after the PDF is created. Under is the consequence preview.
Notes: When opening the file now we have created, we have to entry the actual path of the file. The
FileHandlerused within the above code is just not from the
java.util.loggingclass. Refer here to entry the supply code. One other necessary observe is to request learn file permission from the person. Test the complete supply code of the exercise for extra here.
Under is the mission pattern code:
Exporting knowledge into PDF is a cool function that’s really easy to implement so long as we all know the underlying idea of how an iText doc provides a component.
To sum up, we will merely make use of the library to offer a PDF export function in our app with out having to request our backend server to take action.
Hopefully, that is one thing to study. Pleased coding and cheers.