How to Create PDF From Template in Java

Java is a popular programming language used for developing Web applications, Desktop applications, and Mobile applications. One common task in many applications is the generation of PDF files from templates or HTML files as input data.

PDF generation is a common requirement in many applications, especially those that deal with printing or generating reports. While there are many libraries available for PDF generation in Java, IronPDF is one of the most popular and powerful libraries available. IronPDF provides a range of features that make it easy to create and manipulate PDF files in Java. It can be used to create PDF files from HTML templates.

One of the great features of IronPDF for Java is its ability to work with PDF templates. A PDF template is a pre-designed PDF file that contains placeholders for dynamic content. Using IronPDF, you can easily replace these placeholders with actual data to generate a customized new document in PDF format.

IronPDF

IronPDF is a Java library that is developed and maintained by Iron Software. It provides an easy-to-use interface that abstracts away many of the complexities of PDF generation, allowing developers to focus on the content of their PDFs rather than the details of how the files are generated. IronPDF also provides a range of features that make it easy to work with PDF templates, fillable forms, and digital signatures.

This tutorial will walk you through the steps required to create a PDF file from a template using IronPDF in Java.

Our first step is to create a project.

Step 1: Create a new Java project

Here are the steps to create a new Java project using IntelliJ IDEA:

  1. Open IntelliJ IDEA and select "Create New Project" from the welcome screen or from the "File" menu.
  2. Select "Java" from the left-hand menu and choose the JDK version that you want to use for your project. Click "Next."
  3. Choose a project name and location for your project, and select the project type. You can choose from a number of different project types, such as "Java Application," "Java Library," or "JavaFX Application." Click "Next."
  4. Configure the project settings. You can specify the project SDK, project language level, and other settings. You can also choose to create a module or select an existing one. Click "Next."
  5. Choose the project template. You can choose to create a blank project, a project with a sample code, or import an existing project. Click "Finish."

How to Create PDF From Template in Java: Figure 1 - Create new Java Project Using IntelliJ IDEA

Step 2: Add the IronPDF Library to Your Project

The second step is to add the IronPDF library to your Java project using XML file. You can do this by adding the following dependency to your project’s pom.xml file:

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

Step 3: Create the PDF Template

Next, you need to create a PDF template that you will use to generate your PDF file. You can create your PDF template using any PDF editor. The template can include placeholders that will be replaced with dynamic data at runtime.

Suppose we have to give certificates to 50 students. Now it is a very hectic task to create separate certificates for each user. We can use a template and just change a name using our program as demonstrated below.

How to Create PDF From Template in Java: Figure 2 - Certificate Template image instance

Step 4: Create PDF Documents from Template

After creating the PDF template certificate, we need to load it into our Java application. We can use the IronPDF PdfDocument class to load the PDF template into memory. Here is an example code snippet that shows how to load a PDF template using IronPDF:

PdfDocument PdfDoc = PdfDocument.fromFile(Paths.get("CERTIFICATE.pdf"));
JAVA

Now, we will write code example that will create 5 certificates based on our given template.


//throws exception if file operations are not handled correctly
public static void main(String[] args) throws IOException {

    String [] studentName = new String[] {"Georgia Wade","Juliet Dave", "Olive Seth","Miles Jorg","Oscar Den"};
    for (String name: studentName) {
        PdfDocument PdfDoc = PdfDocument.fromFile(Paths.get("CERTIFICATE.pdf"));
        PdfDoc.replaceText(PageSelection.firstPage(),"Recipient Name",name);
        PdfDoc.saveAs(Paths.get("/Certificate/"+name+".pdf"));
    }
}
JAVA

Following are the Output logs:

How to Create PDF From Template in Java: Figure 3 - Output

The above code creates an array of student names and then uses the IronPDF library to replace a placeholder text in a pre-existing PDF template with each student's name and then saves a new copy of the PDF with the student's name as the file name.

Here's how the code works:

  1. The studentName array is defined and initialized with five student names.
  2. The for loop iterates through each name in the studentName array.
  3. The PdfDocument.fromFile method loads the PDF template file named "CERTIFICATE.pdf" into a PdfDocument object.
  4. The PdfDoc.replaceText method is used to replace the text "Recipient Name" in the PDF template with the current student's name.
  5. The PdfDoc.saveAs method saves the modified PDF file with the student's name as the file name in the "/Certificate" directory.
  6. The loop continues until all student names have been processed.

In this way, we have generated multiple certificates, each with a unique student name, based on a single PDF template. We can generate PDF documents with any template.

Generated PDF Files

How to Create PDF From Template in Java: Figure 4 - PDF Outputs

Certificate Output File

Following is the certificate generated by our program.

How to Create PDF From Template in Java: Figure 5 - Certificate Output

Step 5: Create PDF Template from HTML Template

In this example, we will use HTML file to create a PDF template and then will use that template to generate a PDF document.

I will use the following HTML file for demonstrating the example.

How to Create PDF From Template in Java: Figure 6 - HTML Output

Consider the following code example to create a new document from the given HTML format.


public static void main(String[] args) throws IOException {
    Path fileName = Path.of("D:\\index.html");
    String userName = "Mike";
    String title = "Sample PDF File";
    String body = "This is body of our template PDF";
    String htmlStr = Files.readString(fileName);
    htmlStr = htmlStr.replace("{UserName}", userName);
    htmlStr = htmlStr.replace("{Title}", title);
    htmlStr =htmlStr.replace("{message}", body);
    PdfDocument PdfDoc = PdfDocument.renderHtmlAsPdf(htmlStr);
    PdfDoc.saveAs(Paths.get("/htmlTemplate/" + userName + ".pdf"));
}
JAVA

The above code reads the content of an HTML file, replaces placeholders in the HTML file with dynamic data, renders the HTML as a PDF document using the IronPDF library, and saves the generated PDF document in a specific directory.

Here's a step-by-step explanation of what the code does:

  1. The code begins by creating a Path object that points to an HTML file on the local file system. In this case, the file is located at "D:\index.html".
  2. Three variables are declared and initialized with some sample data: userName, title, and body.
  3. The content of the HTML file is read into a string variable called htmlStr using the Files.readString method.
  4. The String.replace method is used to replace three placeholders ({UserName}, {Title}, and {message}) in the HTML file with the corresponding dynamic data.
  5. The PdfDocument.renderHtmlAsPdf method is called with the modified HTML string as an argument to render the HTML as a PDF document. The resulting PDF document is stored in a PdfDocument object called PdfDoc.
  6. The PdfDoc.saveAs method is called to save the generated PDF document to a directory called "htmlTemplate" on the local file system, with the filename constructed from the userName variable.

How to Create PDF From Template in Java: Figure 7 - Output

In this way, we can create PDF files from HTML templates in a very easy way.

We can replace this watermark by getting a free trial or purchasing a commercial license.

Conclusion

In this article, we have explored how to use IronPDF for Java to generate PDF files. IronPDF provides a simple and powerful interface that allows you to create and manipulate PDF files with ease. With IronPDF, you can easily create professional-looking PDF documents that can be used for a variety of purposes, such as generating reports, invoices, and other types of documents.

IronPDF is also highly customizable, with options to control the appearance and layout of PDF files. Developers can specify page margins, font sizes, colors, and other properties to create PDF files that match their specific requirements.

Overall, IronPDF is a powerful and flexible library for PDF generation in Java. With its easy-to-use interface and wide range of features, IronPDF is a great choice for any application that requires PDF generation.

Download the software product.