In this iText tutorial, we are writing various code examples to read a PDF file and write a PDF file. iText library helps in dynamically generating the .pdf files from Java applications. The given code examples are categorized into multiple sections based on the functionality they achieve. With …
In this iText tutorial, we are writing various code examples to read a PDF file and write a PDF file. iText library helps in dynamically generating the .pdf files from Java applications.
The given code examples are categorized into multiple sections based on the functionality they achieve. With each example, I have attached a screenshot of the generated PDF file to visualize what exactly the code is writing in the PDF file. You may extend these examples to suit your needs.
1. iText Library
On the brighter side, iText is an open-source library. Note that though iText is open source, you still need to purchase a commercial license if you want to use it for commercial purposes.
iText is freely available from https://itextpdf.com/. The iText library is powerful and supports the generation of HTML, RTF, and XML documents and generating PDFs.
We can choose from various fonts to be used in the document. Also, the structure of iText allows us to generate any of the above-mentioned type of documents with the same code. Isn’t it a great feature, right?
The iText library contains classes to generate PDF text in various fonts, create tables in PDF documents, add watermarks to pages, and so on. There are many more features available with iText which I will leave on you to explore.
To add iText into your application, include the following maven repository into our pom.xml file.
Or we can download the latest jar files from its maven repository.
2. Core Classes
Let’s list down and get familiar with the essential classes we will use in this application.
com.itextpdf.text.Document : This is the most important class in iText library and represent PDF document instance. If you need to generate a PDF document from scratch, you will use the Document class. First you must create a Document instance. Then you must open it. After that you add content to the document. Finally you close the Document instance.
com.itextpdf.text.Paragraph : This class represents a indented “paragraph” of text. In a paragraph you can set the paragraph alignment, indentation and spacing before and after the paragraph.
com.itextpdf.text.Chapter : This class represents a chapter in the PDF document. It is created using a Paragraph as title and an int as chapter number.
com.itextpdf.text.Font : This class contains all specifications of a font, such as family of font, size, style, and color. Various fonts are declared as static constants in this class.
com.itextpdf.text.List : This class represents a list, which, in turn, contains a number of ListItems.
com.itextpdf.text.pdf.PDFPTable : This is a table that can be put at an absolute position but can also be added to the document as the class Table.
com.itextpdf.text.Anchor : An Anchor can be a reference or a destination of a reference. A link like we have in HTML pages.
com.itextpdf.text.pdf.PdfWriter : When this PdfWriter is added to a certain PdfDocument, the PDF representation of every Element added to this Document will be written to the outputstream attached to writer (file or network).
Let’s start writing our example codes with the typical Hello World application. I will create a PDF file with a single statement in the content.
JavaPdfHelloWorld.java
importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importcom.itextpdf.text.Document;importcom.itextpdf.text.DocumentException;importcom.itextpdf.text.Paragraph;importcom.itextpdf.text.pdf.PdfWriter;publicclassJavaPdfHelloWorld{publicstaticvoidmain(String[] args){Document document =newDocument();try{PdfWriter writer =PdfWriter.getInstance(document,newFileOutputStream("HelloWorld.pdf"));
document.open();
document.add(newParagraph("A Hello World PDF document."));
document.close();
writer.close();}catch(DocumentException e){
e.printStackTrace();}catch(FileNotFoundException e){
e.printStackTrace();}}}
Hello World Program Output as Pdf
4. Setting File Attributes to PDF
This example shows how to set various attributes like author name, created date, creator name or simply title of the pdf file.
Document document =newDocument();try{PdfWriter writer =PdfWriter.getInstance(document,newFileOutputStream("SetAttributeExample.pdf"));
document.open();
document.add(newParagraph("Some content here"));//Set attributes here
document.addAuthor("Lokesh Gupta");
document.addCreationDate();
document.addCreator("HowToDoInJava.com");
document.addTitle("Set Attribute Example");
document.addSubject("An example to show how attributes can be added to pdf files.");
document.close();
writer.close();}catch(Exception e){
e.printStackTrace();}
SetAttributeExample Pdf Output
5. Adding Images to PDF
An example to show how we can add images to PDF files. The example contains adding images from the file system as well as URLs. Also, I have added code to position the pictures within the document.
Document document =newDocument();try{PdfWriter writer =PdfWriter.getInstance(document,newFileOutputStream("AddImageExample.pdf"));
document.open();
document.add(newParagraph("Image Example"));//Add ImageImage image1 =Image.getInstance("temp.jpg");//Fixed Positioning
image1.setAbsolutePosition(100f,550f);//Scale to new height and new width of image
image1.scaleAbsolute(200,200);//Add to document
document.add(image1);String imageUrl ="http://www.eclipse.org/xtend/images/java8_logo.png";Image image2 =Image.getInstance(newURL(imageUrl));
document.add(image2);
document.close();
writer.close();}catch(Exception e){
e.printStackTrace();}
AddImageExample Pdf Output
6. Generating a Table in PDF
Below example shows how to add tables in a pdf document.
publicstaticvoidmain(String[] args){Document document =newDocument();try{PdfWriter writer =PdfWriter.getInstance(document,newFileOutputStream("AddTableExample.pdf"));
document.open();PdfPTable table =newPdfPTable(3);// 3 columns.
table.setWidthPercentage(100);//Width 100%
table.setSpacingBefore(10f);//Space before table
table.setSpacingAfter(10f);//Space after table//Set Column widthsfloat[] columnWidths ={1f,1f,1f};
table.setWidths(columnWidths);PdfPCell cell1 =newPdfPCell(newParagraph("Cell 1"));
cell1.setBorderColor(BaseColor.BLUE);
cell1.setPaddingLeft(10);
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);PdfPCell cell2 =newPdfPCell(newParagraph("Cell 2"));
cell2.setBorderColor(BaseColor.GREEN);
cell2.setPaddingLeft(10);
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);PdfPCell cell3 =newPdfPCell(newParagraph("Cell 3"));
cell3.setBorderColor(BaseColor.RED);
cell3.setPaddingLeft(10);
cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);//To avoid having the cell border and the content overlap, if you are having thick cell borders//cell1.setUserBorderPadding(true);//cell2.setUserBorderPadding(true);//cell3.setUserBorderPadding(true);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
writer.close();}catch(Exception e){
e.printStackTrace();}}
AddTableExample Pdf Output
7. Creating List of Items in PDF
Below example will help you understand how to write lists in pdf files using the iText library.
To complete this tutorial, let’s see an example of reading and modifying a PDF file using PDFReader class provided by the iText library itself. In this example, I will read content from a PDF and add some random content to all its pages.
This is the last example in the list, and in this example, I am writing the content of created PDF file into the output stream attached to the HttpServletResponse object. This will be needed when you stream the PDF file in a client-server environment.
A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies.
An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Comments