How to Generate PDFs with iText in Spring Boot – A Step‑by‑Step Guide
This tutorial walks you through setting up iText in a Spring Boot 2.3.10 project, creating a Word‑based PDF template, configuring Adobe Acrobat form fields, and implementing a Java utility class to generate and serve personalized PDFs via a REST endpoint.
Environment: Spring Boot 2.3.10.RELEASE with iTextPDF 5.5.13.2
Dependencies
<code><dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency></code>Note: The
itext-asiandependency is optional for compilation but required to display Asian characters correctly.
Creating the Template
First create a template using Microsoft Word.
Save the Word document as a PDF file.
Open the saved PDF with Adobe Acrobat 9 Pro.
1. Open Adobe Acrobat 9 Pro
Click the Form Wizard in the Forms menu.
Note: The arrow points to a text field that must be added to capture the position for inserting an image.
PDF Generation Utility Class
<code>public static void genPdf(Student student, HttpServletResponse response) {
try {
ClassPathResource resource = new ClassPathResource("tml/pdf/student.pdf");
PdfReader pdfReader = new PdfReader(resource.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(pdfReader, baos);
AcroFields af = stamper.getAcroFields();
af.setField("name", student.getName());
af.setField("major", student.getMajor());
af.setField("sno", student.getSno());
af.setField("place", student.getPlace());
// Insert image
String imgUrl = new ClassPathResource("static/1.png").getURL().getPath();
FieldPosition position = af.getFieldPositions("header").get(0);
int pageNo = position.page;
Rectangle signRect = position.position;
float x = signRect.getLeft();
float y = signRect.getBottom();
Image image = Image.getInstance(imgUrl);
PdfContentByte under = stamper.getOverContent(pageNo);
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
image.setAbsolutePosition(x, y);
under.addImage(image);
// Flatten the form so the PDF cannot be edited
stamper.setFormFlattening(true);
stamper.close();
// Respond to client
String downloadFileName = new String((student.getName() + "个人信息.pdf").getBytes("utf-8"), "iso8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, os);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(baos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
response.setContentType("application/pdf");
os.flush();
os.close();
} catch (Exception e) {
logger.error("生成PDF错误:{}", e);
}
}</code>API Endpoint
<code>@GetMapping("/download")
public void download() {
Student student = new Student();
student.setMajor("计算机生命与科学");
student.setName("李逵");
student.setPlace("北京");
student.setSno("S001");
PdfUtil.genPdf(student, response);
}</code>Generated Document
Done!!!
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
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.