Generating PDF Templates with iText in Java: Step-by-Step Guide
This article demonstrates how to create and fill PDF templates using a PDF editor and Java iText library, covering importing Word documents, inserting text, option, and image fields (including signatures and stamps), and provides complete code examples for generating customized PDFs.
This tutorial explains how to build and populate PDF templates using a PDF editor (e.g., Foxit) and the Java iText library.
Using a PDF editor to create the template
1. Import a prepared Word document into the PDF editor – the author uses Foxit PDF editor, but Adobe Acrobat works as well (usually paid).
2. Insert a text field – right‑click the field, set its name and properties.
3. Insert an option (checkbox/radio) field – remember to set the display mode to "label only".
4. Insert image fields for signature and seal – place placeholders where the signature and official stamp will be inserted later.
5. Save the completed template .
Note: make sure the field borders and background are set to "none" so that inserted images are not covered.
Java implementation with iText
Required Maven dependencies:
<!-- pdf -->
com.itextpdf
itextpdf
5.5.13.2
com.itextpdf
itext-asian
5.2.0
com.itextpdf.tool
xmlworker
5.5.11Key Java code (simplified):
package com.tencent.qcloud.roomservice.webrtc.utils;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.util.Map;
/**
* pdf模板操作
*/
public class PdfTest {
public static void main(String[] args) {
// Test execution
FillTemplate(
"C:\\test\\申请表.pdf",
"C:\\test\\新申请表.pdf",
"杜小七",
"辽宁大连",
"跑步",
"Yes",
"Yes",
"Yes",
"C:\\test\\电子签名.png",
"C:\\test\\公章.png"
);
}
/**
* 根据模板生成pdf
*/
public static void FillTemplate(String sourcesPath, String targetPath, String name,
String address, String hobby, String select_1,
String select_2, String select_3,
String signPath, String gongzhangPath) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("address", address);
jsonObject.put("hobby", hobby);
jsonObject.put("select_1", select_1);
jsonObject.put("select_2", select_2);
jsonObject.put("select_3", select_3);
PdfReader reader = null;
PdfStamper stamp = null;
try {
reader = new PdfReader(sourcesPath);
stamp = new PdfStamper(reader, new FileOutputStream(targetPath));
AcroFields form = stamp.getAcroFields();
BaseFont song = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
for (Map.Entry
entry : jsonObject.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
if (key.startsWith("select")) {
form.setField(key, value, true);
} else {
form.setFieldProperty(key, "textfont", song, null);
form.setField(key, value);
}
}
insertImage(form, stamp, "sign", signPath);
insertImage(form, stamp, "gongzhang", gongzhangPath);
stamp.setFormFlattening(true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamp != null) try { stamp.close(); } catch (Exception ignored) {}
if (reader != null) try { reader.close(); } catch (Exception ignored) {}
}
}
/**
* 在指定域插入图片(签名或公章)
*/
public static boolean insertImage(AcroFields form, PdfStamper stamper,
String fieldName, String url) {
try {
int pageNo = form.getFieldPositions(fieldName).get(0).page;
Rectangle rect = form.getFieldPositions(fieldName).get(0).position;
Image img = Image.getInstance(url);
img.scaleToFit(rect.getWidth(), rect.getHeight());
img.setAbsolutePosition(rect.getLeft(), rect.getBottom());
PdfContentByte over = stamper.getOverContent(pageNo);
over.addImage(img);
} catch (Exception e) {
return false;
}
return true;
}
}The above code reads the PDF template, fills text and option fields with values from a JSON object, inserts signature and seal images into their respective fields, and writes the final PDF to the target location.
Test execution
An example screenshot of the test run is shown below:
Author: 小七蒙恩 – Source: CSDN Blog
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.