Java Library PDF Generation (Full Code Example)

Java Library PDF generation

Generating PDF's with a Java library is an effective way to create digital documents. A library specializing in creating PDF's provides simple methods that allow users to easily convert and format documents, images, and data into highly interactive PDF's.

There are several open-source PDF libraries like Apache PDF box (Open-Source Java library) that can be used for creating PDF files easily without adding any complications.

In this article, we will explore the IronPDF library, a great tool for creating PDF's in Java.

IronPDF: Java PDF Library

IronPDF is a popular Java PDF library that allows developers to easily create PDF documents, PDF forms, digitally sign PDF files, and more. With IronPDF, you can use existing PDF documents as templates to generate new PDF files, store PDF data in databases for future use, convert PDF's into other formats like HTML, and even merge multiple PDF's into one single file.

IronPDF allows users to add text annotations to personalize the files they create. Furthermore, with IronPDF, you can include security settings, such as passwords or watermarks, within your PDF's. It helps to integrate PDF functionalities into Java programs. IronPDF is an extremely versatile and powerful tool for generating PDF's quickly and securely. Let's see how we can use IronPDF to create PDF files.

Generate PDF files using IronPDF

IronPDF is an invaluable tool for creating PDF files. It has all the features you need to quickly convert documents, webpages, and images into stable, secure PDF's that can be shared easily. Let's install IronPDF in our program.

Install IronPDF Java PDF library

To install IronPDF Java in a Maven project, you can add the following dependencies to your project's pom.xml file:

<dependency>
   <groupId>com.ironsoftware</groupId>
   <artifactId>com.ironsoftware</artifactId>
   <version>2024.2.1</version>
</dependency>
XML

This will add the IronPDF for Java library and the SLF4J logger that it uses. It is recommended to use the latest version of IronPDF for Java. Once you have added the dependencies, you can run mvn install to install the dependencies in your local repository and your project will be ready to use IronPDF for Java.

Java Code for Creating PDF documents

This code is written in Java and uses the IronPDF library to convert HTML to a PDF document.

// Import statement for IronPDF Java  
import com.ironsoftware.ironpdf.*;  
import java.io.IOException;  
import java.nio.file.Paths;  
public class Main {  
    public static void main(String[] args) throws IOException {
        // Apply your license key
        License.setLicenseKey("YOUR-LICENSE-KEY");  
        // Set a log path  
        Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));  
        // Render the HTML as a PDF. Stored in myPdf as type PdfDocument  
        String HTML = "<!DOCTYPE html>\r\n"
+ "<html>\r\n"
+ "  <head>\r\n"
+ "    <link href='https://fonts.googleapis.com/css2?family=Popin&display=swap' rel='stylesheet'>\r\n"
+ "    <style>\r\n"
+ "      /* Add CSS styles for the invoice here */\r\n"
+ "      body{\r\n"
+ "        font-family: 'Popin', cursive;\r\n"
+ "      }\r\n"
+ "      .invoice {\r\n"
+ "        width: 80%;\r\n"
+ "        margin: 0 auto;\r\n"
+ "        border: 1px solid #ccc;\r\n"
+ "        padding: 20px;\r\n"
+ "        background-color: #f5f5f5;\r\n"
+ "        color: #333;\r\n"
+ "      }\r\n"
+ "      .invoice h1 {\r\n"
+ "        text-align: center;\r\n"
+ "      }\r\n"
+ "      .invoice .invoice-info {\r\n"
+ "        display: flex;\r\n"
+ "        justify-content: space-between;\r\n"
+ "        margin-bottom: 20px;\r\n"
+ "      }\r\n"
+ "      .invoice .invoice-info div {\r\n"
+ "        width: 45%;\r\n"
+ "      }\r\n"
+ "      .invoice table {\r\n"
+ "        width: 100%;\r\n"
+ "        border-collapse: collapse;\r\n"
+ "      }\r\n"
+ "      .invoice table th, .invoice table td {\r\n"
+ "        border: 1px solid #ccc;\r\n"
+ "        padding: 10px;\r\n"
+ "      }\r\n"
+ "      .invoice table th {\r\n"
+ "        text-align: left;\r\n"
+ "        background-color: #f5f5f5;\r\n"
+ "      }\r\n"
+ "      .invoice table td {\r\n"
+ "        text-align: right;\r\n"
+ "      }\r\n"
+ "      .invoice table td.total {\r\n"
+ "        font-weight: bold;\r\n"
+ "      }\r\n"
+ "    </style>\r\n"
+ "  </head>\r\n"
+ "  <body>\r\n"
+ "    <div class=\"invoice\">\r\n"
+ "      <h1>Invoice</h1>\r\n"
+ "      <div class=\"invoice-info\">\r\n"
+ "        <div>\r\n"
+ "          <p><strong>From:</strong></p>\r\n"
+ "          <p>Your Company Name</p>\r\n"
+ "          <p>123 Main St</p>\r\n"
+ "          <p>City, State ZIP</p>\r\n"
+ "        </div>\r\n"
+ "        <div>\r\n"
+ "          <p><strong>To:</strong></p>\r\n"
+ "          <p>Customer Name</p>\r\n"
+ "          <p>456 Park Ave</p>\r\n"
+ "          <p>City, State ZIP</p>\r\n"
+ "        </div>\r\n"
+ "      </div>\r\n"
+ "      <table>\r\n"
+ "        <thead>\r\n"
+ "          <tr>\r\n"
+ "            <th>Product</th>\r\n"
+ "            <th>Quantity</th>\r\n"
+ "            <th>Price</th>\r\n"
+ "            <th>Total</th>\r\n"
+ "          </tr>\r\n"
+ "        </thead>\r\n"
+ "        <tbody>\r\n"
+ "          <tr>\r\n"
+ "            <td>Product 1</td>\r\n"
+ "            <td>1</td>\r\n"
+ "            <td>$10.00</td>\r\n"
+ "            <td>$10.00</td>\r\n"
+ "          </tr>\r\n"
+ "          <tr>\r\n"
+ "            <td>Product 2</td>\r\n"
+ "            <td>2</td>\r\n"
+ "            <td>$5.00</td>\r\n"
+ "            <td>$10.00</td>\r\n"
+ "          </tr>\r\n"
+ "          <tr>\r\n"
+ "            <td colspan=\"3\" class=\"total\">Total:</td>\r\n"
+ "            <td class=\"total\">$20.00</td>\r\n"
+ "          </tr>\r\n"
+ "        </tbody>\r\n"
+ "      </table>\r\n"
+ "    </div>\r\n"
+ "  </body>\r\n"
+ "</html>";  
PdfDocument myPdf = PdfDocument.renderHtmlAsPdf(HTML);
//Save PDF document
myPdf.saveAs(Paths.get("C://HTMLtoPDF.pdf"));
    }  
}
JAVA

The first step is to apply a license key using the setLicenseKey method. The key is passed as a string argument; in this case, "YOUR-LICENSE-KEY" should be replaced with the actual license key.

The next step is to set a log path using the setLogPath method. This is where the log file for the IronPDF engine will be saved. In this case, it is set to "C:/tmp/IronPdfEngine.log."

The main method is defined, and a PdfDocument object is created by calling the renderHtmlAsPdf method, passing in a string of HTML as the argument. This will convert the HTML to a PDF and store it in the myPdf object.

The final step is to save the myPdf object to a file using the saveAs method. The file location is passed as an argument in the form of a Paths object, in this case, "HTMLtoPDF.pdf."

Here you can see the output of the above program where we create a PDF file using the IronPDF Java PDF library.

Java Library PDF Generation - Figure 1

Results produced from running the above code example. IronPDF renders the HTML contained in the string into a PDF.

Create PDF file from URL

IronPDF can render web pages from a variety of sources, including local networks and external servers.

import com.ironsoftware.ironpdf.*;
import java.io.IOException;
import java.nio.file.Paths;

// Apply your license key
License.setLicenseKey("YOUR-LICENSE-KEY");

// Set a log path
Settings.setLogPath(Paths.get("C:/tmp/IronPdfEngine.log"));

// Render the HTML as a PDF. Stored in myPdf as type PdfDocument;
PdfDocument myPdf = PdfDocument.renderUrlAsPdf("https://ironpdf.com");

// Save the PdfDocument to a file
myPdf.saveAs(Paths.get("url.pdf"));
JAVA

The PdfDocument.renderUrlAsPdf method is specifically designed for this purpose and accepts a string containing the URL of the web page to be converted. The method retrieves the HTML content of the web page and transforms it into a PDF document. IronPDF preserves the appearance of all web components while making interactives (links, form fields, etc.) functional.

The results are below:

Java Library PDF Generation - Figure 2

Converting Web Pages to PDFs by URL using IronPDF

Summary

In conclusion, IronPDF is a valuable Java library with many features for creating and manipulating PDF files. Whether you need to digitally sign a PDF, fill out forms, or perform other tasks, IronPDF makes it easy to do so with minimal coding.

With its free trial and flexible pricing options starting at $749, IronPDF is a cost-effective solution for developers looking to add PDF functionality to their projects.