You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用iText PDF 5.5.4写入PDF段落时触发NullPointerException问题

问题描述

使用Java 17 + iText PDF 5.5.4版本,尝试在现有PDF指定矩形区域写入文本时,调用ColumnText.go()方法触发NullPointerException,异常信息显示Cannot invoke "com.itextpdf.text.pdf.PdfStructureElement.getAttribute(com.itextpdf.text.pdf.PdfName)" because "this.parent" is null。

测试代码如下:

public class Main {
    public static void main(String[] args) {
        try {
            PdfReader reader = new PdfReader("src/main/resources/test_file.pdf");
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("src/main/resources/output.pdf"));

            PdfContentByte cb = stamper.getOverContent(1);
            ColumnText ct = new ColumnText(cb);
            ct.setSimpleColumn(new Rectangle(36, 600, 200, 800));
            ct.addElement(new Paragraph("I want to add this text in a rectangle defined by the coordinates llx = 36, lly = 600, urx = 200, ury = 800"));
            int status = ct.go();
        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}

异常信息:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.itextpdf.text.pdf.PdfStructureElement.getAttribute(com.itextpdf.text.pdf.PdfName)" because "this.parent" is null

问题原因及解决办法

原因

iText 5.5.4是2014年发布的旧版本,完全不兼容Java 9及以上版本(包括Java 17)。Java 9引入的模块系统、反射机制变化,导致iText内部处理PDF结构化内容时,PdfStructureElement的parent字段为空,触发空指针异常。

解决办法

  1. 升级iText版本(推荐)
    将iText 5.x版本升级到5.5.13.3,该版本修复了Java 9+的兼容性问题,可正常在Java 17环境下运行。

  2. 禁用PDF结构化内容(临时 workaround)
    如果无法升级版本,可在创建PdfStamper后添加一行代码关闭结构化内容支持,绕过异常:

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("src/main/resources/output.pdf"));
stamper.setStructuredContent(false); // 添加此行关闭结构化内容

内容的提问来源于stack exchange,提问作者François Vinckel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 03:32:36