Here's 3 Popular Java PDF Libraries
Published: 2023-01-05 07:33:56

As a Java or software developer, you'll know that PDFs are an important format to work with. But did you know that there are libraries specifically designed to help you work with PDFs? This article will introduce three popular PDF libraries and show you how to use them.

If you're creating new PDF documents, these libraries will help make your job easier. Stay tuned for more Java programming tips and tricks!

## 1. [IronPDF](https://ironpdf.com/java)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wcpt80yg6t08e0dw2s7c.png)


IronPDF is a .NET and Java PDF library that makes it easy to generate, modify, and convert PDF files. With IronPDF, you can create PDFs from scratch or convert existing documents to PDF format.

IronPDF provides a wide range of features, including the ability to add text, images, and annotations to PDFs, as well as support for password protection and encryption.

Additionally, IronPDF can be used to integrate PDF functionalities in Java applications like filling out PDF forms and creating bookmarks, as well as tables of contents. Whether you're looking to create a new PDF document or edit an existing one, IronPDF is a great option.

## Code Example

Let's look at code examples showcasing many different functionalities of IronPDF. As shown in the code below, we can create PDF files from any URL. We have to import the IronPDF java package in every file where we want to use IronPDF.

```
import com.ironsoftware.ironpdf.*;
PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://getbootstrap.com/");
myPdf.saveAs(Paths.get("url.pdf"));

```
The output of the code above will display what it has created in the following image. IronPDF preserves the PDF quality and renders all images and buttons with great quality.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5s9opg4uk5hqiw4fqp8.png)

We can create fill-in PDF forms using the code example below.

```
import com.ironsoftware.ironpdf.PdfDocument;  
import com.ironsoftware.ironpdf.render.ChromePdfRenderOptions;  
import java.io.IOException;  
import java.nio.file.*;
 
// #1 Use Case: Create a PDF Form from HTML Form Markup  
Path outputLocation = Paths.get("assets/BasicForm.pdf");  
String formHTML = "<html>"  
  + "<body>"  
  + "<h2>Editable PDF  Form</h2>"  
  + "<form>"  
  + "First name: <br> <input type='text' name='firstname' value=''> <br>"  
  + "Last name: <br> <input type='text' name='lastname' value=''>"  
  + "</form>"  
  + "</body>"  
  + "</html>";  
  
ChromePdfRenderOptions renderOptions = new ChromePdfRenderOptions();  
renderOptions.setCreatePdfFormsFromHtml(true);  
PdfDocument.renderHtmlAsPdf(formHTML, renderOptions).saveAs(outputLocation);  
  
// #2 Use Case: Writing Values to the PDF Form  
PdfDocument form = PdfDocument.fromFile(outputLocation);  
  
// Set the value of the firstname input field.  
form.getForm().setFieldValue("firstname", "Minnie");  
  
// Set the value of the lastname input field.  
form.getForm().setFieldValue("lastname", "Mouse");  
  
// Save the changes to the PDF Form.  
form.saveAs(Paths.get("assets/BasicForm_Filled.pdf"));

```
There are many things that we can do in this PDF document using the IronPDF Java PDF library. You find more information and tutorials about the IronPDF library using the following [link]( https://ironpdf.com/java/examples/using-html-to-create-a-pdf/).

## Pricing

The IronPDF java PDF library price starts from $749 for the lite plan and there are many to choose from depending on your needs.

You can get a free trial for 30 days to test the IronPDF production environment without a watermark. Here is more information about licensing using the following [link](https://ironpdf.com/java/licensing/). 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gk3j7rj3p95nrvo95676.png)


## 2. iText7 Library

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/123amql2az7f91209gx4.png)

iText7 is a PDF library designed specifically to create high-quality PDF documents from scratch. It allows you to create both simple and complex documents in a variety of file formats, including HTML5.

iText7 includes features like digital signatures and encryption so that users can securely share their documents with others over the internet.

With its wide array of features and easy deployment options, iText has become one of the go-to libraries for Java developers when working with PDF formats.

## Create PDF files - Code Example

Using the following code, you can create a simple table in PDFs using the iText library.

```
package com.itextpdf.samples.sandbox.tables;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.UnitValue;

import java.io.File;

public class SimpleTable {
    public static final String DEST = "./target/sandbox/tables/simple_table.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new SimpleTable().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        Document doc = new Document(pdfDoc);

        Table table = new Table(UnitValue.createPercentArray(8)).useAllAvailableWidth();

        for (int i = 0; i < 16; i++) {
            table.addCell("hi");
        }

        doc.add(table);

        doc.close();
    }
}

```
The above code contains a class that will create a table comprised of 16 cells.

This is the resulting output in the following image.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/orl48gm426e8xt5inc1u.png)



We can add a digital signature using the following code.

package com.itextpdf.samples.signatures.chapter02;

```
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.StampingProperties;
import com.itextpdf.signatures.PdfSigner;
import com.itextpdf.signatures.PdfSignatureAppearance;
import com.itextpdf.signatures.IExternalSignature;
import com.itextpdf.signatures.IExternalDigest;
import com.itextpdf.signatures.PrivateKeySignature;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;

public class C2_02_SignHelloWorldWithTempFile {
    public static final String DEST = "./target/signatures/chapter02/";

    public static final String KEYSTORE = "./src/test/resources/encryption/ks";
    public static final String SRC = "./src/test/resources/pdfs/hello.pdf";

    public static final char[] PASSWORD = "password".toCharArray();

    public static final String[] RESULT_FILES = new String[] {
            "hello_signed_with_temp.pdf"
    };

    public void sign(String src, String temp, String dest, Certificate[] chain, PrivateKey pk,
            String digestAlgorithm, String provider, PdfSigner.CryptoStandard subfilter,
            String reason, String location)
            throws GeneralSecurityException, IOException {
        PdfReader reader = new PdfReader(src);

        // Pass the temporary file's path to the PdfSigner constructor
        PdfSigner signer = new PdfSigner(reader, new FileOutputStream(dest), temp, new StampingProperties());

        // Create the signature appearance
        Rectangle rect = new Rectangle(36, 648, 200, 100);
        PdfSignatureAppearance appearance = signer.getSignatureAppearance();
        appearance
                .setReason(reason)
                .setLocation(location)

                // Specify if the appearance before field is signed will be used
                // as a background for the signed field. The "false" value is the default value.
                .setReuseAppearance(false)
                .setPageRect(rect)
                .setPageNumber(1);
        signer.setFieldName("sig");

        IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
        IExternalDigest digest = new BouncyCastleDigest();

        // Sign the document using the detached mode, CMS or CAdES equivalent.
        signer.signDetached(digest, pks, chain, null, null, null, 0, subfilter);
    }

    public static void main(String[] args) throws GeneralSecurityException, IOException {
        File file = new File(DEST);
        file.mkdirs();

        BouncyCastleProvider provider = new BouncyCastleProvider();
        Security.addProvider(provider);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(KEYSTORE), PASSWORD);
        String alias = ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
        Certificate[] chain = ks.getCertificateChain(alias);

        new C2_02_SignHelloWorldWithTempFile().sign(SRC, DEST, DEST + RESULT_FILES[0], chain, pk,
                DigestAlgorithms.SHA256, provider.getName(), PdfSigner.CryptoStandard.CMS,
                "Temp test", "Ghent");
    }
}

```
The above code will add a digital signature, using the latest version of iText7.

## Pricing

There is no pricing plan mentioned on the website. You must get a quote from customer support for purchasing the license. However, you can get some resources for free like iText 7 Core and pdfHTML. Find more information about iText7 licensing using the following [link](https://itextpdf.com/get-your-itext-license).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ufs3bisamvt4k3nm2in.png)



## 3. jPDFProcess

jPDFProcess is a Java library designed specifically to create high-quality PDFs, documents or images from scratch. With this tool you can quickly generate complex documents such as invoices or catalogs with ease thanks to its intuitive API and rich feature set including support for text manipulation, form creation/filling/submission, and more.

Additionally, jPDFProcess also provides an API for digitally signing documents using digital certificates. This makes it ideal for certain document exploitation scenarios like eSignatures or document archiving processes involving digital signatures.

## Code Example

You can use the following code to create PDF files using the jPDFProcess open-source java tool.

`/*
 * This sample java program uses jPDFProcess
 * to create a new PDF file, add a page to it
 * and draw an image and text on the page.
 * 
 */
package jPDFProcessSamples;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.qoppa.pdfProcess.PDFDocument;
import com.qoppa.pdfProcess.PDFGraphics;
import com.qoppa.pdfProcess.PDFPage;

public class CreatePDFWithTextAndImage
{
    public static void main (String [] args)
    {
    	try
    	{
    		// create document
    		PDFDocument pdfDoc = new PDFDocument ();
    	 
    		// create and add a page
    		PDFPage page = pdfDoc.appendNewPage(8.5 * 72, 11 * 72);
    	
    		// get graphics from the page
    		// this object is a Graphics2D Object and you can draw anything 
    		// you would draw on a Graphics2D
    		PDFGraphics g2d = (PDFGraphics) page.createGraphics();
    	
    		// read an image from png,. jpeg, etc... 
    		BufferedImage image = ImageIO.read(new File("C:\\myimage.png"));
    		
    		// draw the image on the page
    		g2d.drawImage(image, 0, 0, null);
        
    		// set the font and color
    		g2d.setFont (PDFGraphics.HELVETICA.deriveFont(24f));
    		g2d.setColor(Color.BLUE);
        
    		// draw text on the graphics object of the page
    		g2d.drawString("NEW TEXT", 200, 100);
    	 
    		// Save the document
    		pdfDoc.saveDocument ("C:\\test.pdf");
    	}
    	catch(Throwable t)
    	{
    		t.printStackTrace();
    	}
    }
}
`
The code above will create a PDF document, add a page on it and draw an image and text on that page.

We can add a watermark to the PDF file using the following code.

package jPDFProcessSamples;

`import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;

import com.qoppa.pdfProcess.PDFDocument;
import com.qoppa.pdfProcess.PDFGraphics;
import com.qoppa.pdfProcess.PDFPage;

public class AddWatermark
{
    public static void main (String [] args)
    {
        try
        {
            // Load document
            PDFDocument pdfDoc = new PDFDocument ("input.pdf", null);
            
            // Loop through all pages
            Font wmFont = PDFGraphics.HELVETICA.deriveFont(64f);
            for (int pageIx = 0; pageIx < pdfDoc.getPageCount(); ++pageIx)
            {
                // Get the page
                PDFPage page = pdfDoc.getPage(pageIx);
                
                // Get a graphics object to draw onto the page
                Graphics2D g2d = page.createGraphics();
                
                // Draw watermark
                g2d.setColor (new Color (160, 160, 160, 160));
                g2d.setFont(wmFont);
                g2d.translate(72, 72 + g2d.getFontMetrics().getAscent());
                g2d.rotate(Math.toRadians(45));
                g2d.drawString ("Confidential", 0, 0);
            }
            
            // Save the document
            pdfDoc.saveDocument ("output.pdf");
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    }
}`

The code above contains a class with a method that will loop through all the pages and a draw watermark on each one.

## Pricing

jPDFProcess is an open-source java library. We can use its PDF features for free.

## Summary

IronPDF is our preferred library of choice, as it offers slightly more features than IText7 and other libraries at a lower cost. We also found IronPDF to be beginner friendly, so a solid choice if you're a junior developer looking for a library to start with.

iText7 does deliver good render outputs and processing speeds. It also has a freemium which you can use in your projects with limited capabilities. However, iText7 does not offer a free trial. It has good documentation but lacks tutorials for beginners. There is no fixed price mentioned on the website for the license. You have to contact support to get a quote.

jPDFProcess is also a good library but lacks many features. Regardless, it is a free library that has useful functionality.

IronPDF has good documentation and tutorials to help you understand the process with almost no code. The license of IronPDF is optimized for all levels of users and starts at $749. IronPDF offers a 30-day trial period to let you test it in production.

In conclusion, all three libraries are high-quality and will help developers get the job done.