How to Generate PDFs with iText in Spring Boot: A Step‑by‑Step Guide
This tutorial walks through setting up iText dependencies, creating a Word‑based PDF template, configuring Adobe Acrobat form fields, and implementing a Spring Boot utility class and endpoint to generate and download customized PDF documents with embedded images.
Environment: springboot2.3.10.RELEASE + itextpdf5.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-asian dependency is not required for compilation, but without it Chinese characters will not display.
Creating the Template
First create a template using Word.
Save the Word document as a PDF.
Open the PDF with Adobe Acrobat 9 Pro.
1. Open Adobe Acrobat 9 Pro
Click the Form Wizard in the Forms menu.
Note: The arrow also indicates that a text field must be drawn to capture position information for inserting an image.
PDF Generation Utility
<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();
// Read image
Image image = Image.getInstance(imgUrl);
// Get page to operate on
PdfContentByte under = stamper.getOverContent(pageNo);
// Scale image to field size
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// Add image
image.setAbsolutePosition(x, y);
under.addImage(image);
// Set output PDF (must flatten to prevent further editing)
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>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>Generate the document
Done!!!
Give a like, thanks
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.