SoFunction
Updated on 2025-04-14

Java implementation reads PDF according to template and replaces specified content

In actual development, you often encounter the need to generate specific PDFs based on PDF template documents, such as contracts, certificates, etc. We can use the iText library to realize the function of reading PDF template documents, replacing specified content, and finally regenerating a new PDF. Next, I will tell you in detail how to do it.

1. Introduce dependencies

If you use Maven to manage your project, add the following dependencies in:

<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.13.3</version>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>itext-asian</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>

Itext-asian This dependency is to support the display of Asian texts such as Chinese.

2. Create a PDF template

First, there must be a PDF template file, in which a specific placeholder is used to represent the content that needs to be replaced. You can use tools such as Adobe Acrobat to add text fields as placeholders in PDFs, such as adding a text field named name to represent a name.

3. Java code implementation

import ;
import .*;
 
import .*;
import ;
import ;
 
public class PdfTemplateProcessor {
    public static void main(String[] args) {
        try {
            // Read PDF template file            PdfReader reader = new PdfReader("");
            // Create an output stream to save the newly generated PDF            FileOutputStream outputStream = new FileOutputStream("");
            // Create a PdfStamper object to manipulate PDF content            PdfStamper stamper = new PdfStamper(reader, outputStream);
 
            // Get PDF form            AcroFields form = ();
            // Settings support Chinese            BaseFont baseFont = ("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            (baseFont);
 
            // Prepare the data to be replaced            Map&lt;String, String&gt; data = new HashMap&lt;&gt;();
            ("name", "Zhang San");
            ("date", "2024-10-01");
 
            // Replace the placeholder in the form            for (&lt;String, String&gt; entry : ()) {
                String fieldName = ();
                String fieldValue = ();
                (fieldName, fieldValue);
            }
 
            // Close form editing            (true);
            // Close stamper and reader            ();
            ();
            ();
 
            ("The new PDF document was generated successfully!");
        } catch (IOException | DocumentException e) {
            ();
            ("Creating a new PDF document failed:" + ());
        }
    }
}

4. Code explanation

1. Read PDF template file

PdfReader reader = new PdfReader("");
FileOutputStream outputStream = new FileOutputStream("");
PdfStamper stamper = new PdfStamper(reader, outputStream);

Read the file through PdfReader and use FileOutputStream to create an output stream that saves the newly generated PDF file. PdfStamper is an important class used in iText to operate PDF content. It allows us to modify PDF content without changing the original file structure.

2. Get PDF forms and set Chinese support

AcroFields form = ();
BaseFont baseFont = ("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
(baseFont);

AcroFields represents the form field in a PDF, and the form is obtained through (). To support Chinese display, use the method to create a Chinese-supported font and add it to the form.

3. Prepare the data to be replaced

Map&lt;String, String&gt; data = new HashMap&lt;&gt;();
("name", "Zhang San");
("date", "2024-10-01");

Create a Map object that maps the placeholder (form field name) to the content to be replaced.

4. Replace the placeholder in the form

for (<String, String> entry : ()) {
    String fieldName = ();
    String fieldValue = ();
    (fieldName, fieldValue);
}

Iterate over the Map and use the method to replace the placeholder in the form field with the actual content.

5. Close form editing and save new PDF

(true);
();
();
();

(true) Used to flatten the form field to prevent the form field from being edited again. Finally, close the stamper, reader, and output streams to save the newly generated PDF file.

The above is the detailed content of Java implementation that reads PDFs based on templates and replaces specified content. For more information about Java reading PDFs, please pay attention to my other related articles!