itext 7.1 添加段落到文档

Itext 7.1 add paragraph to document

在 iText 7.0 中,我使用以下代码将内容添加到 pdf 文档,一切都按预期工作。

ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(out);
PdfDocument pdfDocument = new PdfDocument(writer);
try {
    LicenseKey.loadLicenseFile(".../key.xml");
    Document document = new Document(pdfDocument);
    document.add(new Paragraph("Some content"));
                //---more code----

使用 7.1.0 版时,我在

行遇到异常
document.add(new Paragraph("Some content"));

异常:

See nested exception;
nestedexceptionis:com.itextpdf.kernel.PdfException: document.has.no.pages

当我捕捉到 document.add 调用期间抛出的 Throwable 时,我得到一个

 NoSuchMethodError
com/itextpdf/layout/Document.add(Lcom/itextpdf/layout/element/IBlockElement;)Lcom/itextpdf/layout/Document;

尝试addNewPage()你的PdfDocument

在评论中发现实际上有一个

NoSuchMethodError com/itextpdf/layout/Document.add(Lcom/itextpdf/layout/element/IBlockElement;)Lcom/itextpdf/layout/Document;

导致此问题。

从 7.0.2 开始,iText 7 布局 Document class 有一个方法

public Document add(IBlockElement element)

7.0.1 之前没有界面IBlockElementadd 方法签名不同并且显式使用了泛型

public <T extends IElement> Document add(BlockElement<T> element)

此更改已于 2016 年 11 月 25 日 13:45:32 在 git 提交 7cfc57b25c9faca96bc15e39163730002d9e4c9a 中提交。

因此,您似乎至少使用 iText 7.0.2 编译了代码,但 运行 它最多使用 iText 7.0.1。

请确保您 运行 您的代码使用的 iText 版本不早于您编译时使用的版本。