Home » Java » Core Java » How to create PDF File in Java – iText Example

About Javin Paul

Javin Paul
I have been working in Java, FIX Tutorial and Tibco RV messaging technology from past 7 years. I am interested in writing and meeting people, reading and learning about new subjects.

How to create PDF File in Java – iText Example

Hello guys, generating PDF files in today’s enterprise applications is quite common. Doing this with Java is not an easy task as Java does not gives default api’s to handle PDF files. No worries, iText jar is for you. Earlier, I have shared about iText vs Apache FOP, two of the most popular libraries to create PDF files and today, I will show you an example of how to create a PDF files using the iText library in Java. If you are not familiar,  iText is a free Java-PDF library that allows you to generate PDF files on the fly (dynamically). iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.

By the way, iText is not an end-user tool. Typically you won’t use it on your Desktop as you would use Acrobat or any other PDF application. Rather, you’ll build iText into your own applications so that you can automate the PDF creation and manipulation process.

Here are a couple of things for which you can use iText (Java-PDF Library):

  • Serve PDF to a browser
  • Generate dynamic documents from XML files or databases
  • Use PDF’s many interactive features
  • Add bookmarks, page numbers, watermarks, etc.
  • Split, concatenate, and manipulate PDF pages
  • Automate filling out of PDF forms
  • Add digital signatures to a PDF file
  • Technical Requirements to use iText
  • You should have JDK 1.4 or later to integrate iText PDF generation in your application.

This is also one of the top 20 Java libraries I recommend Java programmer to learn. Learning these libraries will greatly improve your ability as a Java developer. 

Getting iText

You can either download iText jar from its home page http://www.lowagie.com/iText/download.html

iText core: iText-5.5.13.jar

or you can also download from the Maven repository by adding iText dependency on your pom.xml file. 

iText Maven Dependency

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

iText Gradle Dependency

1
2
compile group: 'com.itextpdf', name: 'itextpdf', version: '5.5.13'

iText JARS :

C:\m2\repository\com\lowagie\itext\4.2.1\itext-4.2.1.jar

C:\m2\repository\org\bouncycastle\bctsp-jdk14\1.38\bctsp-jdk14-1.38.jar

C:\m2\repository\org\bouncycastle\bcprov-jdk14\1.38\bcprov-jdk14-1.38.jar

C:\m2\repository\org\bouncycastle\bcmail-jdk14\1.38\bcmail-jdk14-1.38.jar

C:\m2\repository\jfree\jfreechart\1.0.12\jfreechart-1.0.12.jar

C:\m2\repository\jfree\jcommon\1.0.15\jcommon-1.0.15.jar

C:\m2\repository\org\swinglabs\pdf-renderer\1.0.5\pdf-renderer-1.0.5.jar

How to create PDF files/documents in Java – iText library Example

Here is a complete code example to generate a PDF file using the 
iText library in Java.

01
02
03
04
05
06
07
08
09
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
 
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
 
/**
* Java Program to generate PDF document using iText library.
*
* @author Javin
*/
public class Testing {
 
    public static void main(String args[]) {
 
        OutputStream file = null;
        try {
            file = new FileOutputStream(new File("Contacts.pdf"));
 
            // Create a new Document object
            Document document = new Document();
 
            // You need PdfWriter to generate PDF document
            PdfWriter.getInstance(document, file);
 
            // Opening document for writing PDF
            document.open();
 
            // Writing content
            document.add(new Paragraph("Hello World, Creating PDF document in Java is easy"));
            document.add(new Paragraph("You are customer # 2345433"));
            document.add(new Paragraph(new Date(new java.util.Date().getTime()).toString()));
 
                   // Add meta data information to PDF file
            document.addCreationDate();
            document.addAuthor("Javarevisited");
            document.addTitle("How to create PDF document in Java");
            document.addCreator("Thanks to iText, writing into PDF is easy");
 
 
            // close the document
            document.close();
 
            System.out.println("Your PDF File is succesfully created");
 
        } catch (Exception e) {
            e.printStackTrace();
 
        } finally {
 
            // closing FileOutputStream
            try {
                if (file != null) {
                    file.close();
                }
            } catch (IOException io) {/*Failed to close*/
 
            }
 
        }
 
    }
 
}
 
Output:
Your PDF File is successfully created

Adding metadata/Setting attributes of PDF using free Java-PDF library

While you generate a PDF, you may want to set its different attribute like: author name, title, file description etc. iText jar can help you to set different attributes of a PDF file. Document object provide different methods to add various attributes to a PDF file.

1
2
3
4
document.addCreationDate();
document.addAuthor("");
document.addTitle("How to create PDF document in Java");
document.addCreator("Thanks to iText, writing into PDF is easy");

That’s all on how to generate PDF files in Java using iText. Lots of open source framework uses iText to provide PDF support in their application. for example display tag, which is a popular JSP tag library to generate dynamic HTML tables, allow you to export table in PDF format. It does this conversion by using iText library, so all you need is to include iText.jar in your classpath and boom, you can export PDF documents from Java application.

If you like this article, you may find the following articles interesting as well:

Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues too. If you have any feedback or questions then please share your thoughts by commenting, I highly appreciate your comment and try to reply as soon as possible. 

Published on Java Code Geeks with permission by Javin Paul, partner at our JCG program. See the original article here: How to create PDF File in Java – iText Example

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
2 Comments Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ruurd Pels
ruurd
1 year ago

That is I think almost the worst tool to create a PDF one can imagine. Yes it might be easy to use but alas the end product really is unsightly. Why not use a tool that generates letterpress quality output and has a text based input as well? Ever heard of TeX by chance?

SuperPat
SuperPat
1 year ago

Why do not you use the actively developed OpenPDF fork (https://github.com/LibrePDF/OpenPDF) instead this unmaintained API version?

Last edited 1 year ago by SuperPat