Monday, July 3, 2023

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

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

iText Gradle Dependency
// https://mvnrepository.com/artifact/com.itextpdf/itextpdf
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

How to create PDF files in Java using iText


Here is a complete code example to generate a PDF file using the iText library in Java.
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.

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 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. 


No comments :

Post a Comment