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.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
How to Generate PDFs with iText in Spring Boot – A Step‑by‑Step Guide

Environment: Spring Boot 2.3.10.RELEASE with iTextPDF 5.5.13.2

Dependencies

<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>

Note: The itext-asian dependency is optional for compilation but required to display Asian characters correctly.

Creating the Template

First create a template using Microsoft Word.

Word template
Word template

Save the Word document as a PDF file.

Open the saved PDF with Adobe Acrobat 9 Pro.

1. Open Adobe Acrobat 9 Pro

Adobe Acrobat
Adobe Acrobat

Click the Form Wizard in the Forms menu.

Form Wizard
Form Wizard
Form field layout
Form field layout

Note: The arrow points to a text field that must be added to capture the position for inserting an image.

Position field
Position field

PDF Generation Utility Class

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);
    }
}

API Endpoint

@GetMapping("/download")
public void download() {
    Student student = new Student();
    student.setMajor("计算机生命与科学");
    student.setName("李逵");
    student.setPlace("北京");
    student.setSno("S001");
    PdfUtil.genPdf(student, response);
}

Generated Document

Resulting PDF
Resulting PDF

Done!!!

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaSpring BootiTextpdf-generation
Spring Full-Stack Practical Cases
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.