java - iText - 第二次尝试生成 PDF 失败

标签 java pdf itext

我有一个 Java 桌面应用程序,它使用 iText 从结果集中生成 PDF。第一次生成 PDF 时,它工作正常。当您尝试生成第二个时,问题就来了。它抛出一个 DocumentException 说明文档已关闭。我试图找到其他人遇到这个问题的例子,但我想出的很少,这让我相信我犯了一个非常简单的错误,但我找不到它。

下面的代码是调用报表类的事件处理程序的片段:

RptPotReport report = new RptPotReport();
try {
    report.rptPot();
} catch (DocumentException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

这里是报表类本身的代码。第二次运行此代码时发生错误:

public class RptPotReport {

    public static void main(String[] args) throws IOException, DocumentException, SQLException {
        new RptPotReport().rptPot();
    }

    String fileOutput = "Potting Report.pdf";

    public void rptPot() throws DocumentException, IOException {
        File f = new File("Potting Report.pdf");
        if (f.exists()) {
            f.delete();
        }

        Document document = new Document();
        document = pdfSizes.getPdfLetter();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileOutput));
        document.open();

        Phrase title = new Phrase();
        title.add(new Chunk("Potting Report"));

        document.add(title); // ******* DocumentException here: "The document has been closed. You can't add any Elements."
        document.close();

        try {
            File pdfFile = new File(fileOutput);
            if (pdfFile.exists()) {
                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(pdfFile);
                } else {
                    System.out.println("Awt Desktop is not supported!");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

编辑:根据某人的建议,我尝试从第二个线程调用 RptPotReport,但这并没有改变任何东西。进一步研究,iText 的 Document 类在实例化时创建了一个新线程。所以我又回到了起点,仍然卡住了。

最佳答案

这一行在您的应用程序中究竟做了什么:

document = pdfSizes.getPdfLetter();

如果没有代码和您的解释,该行似乎将 document 变量的引用设置为您从 pdfSizes.getPdfLetter() 收到的变量,这在运行之间重复使用,因此您不再有 new Document() 语句的引用。

我倾向于认为 pdfSizes.getPdfLetter() 方法有问题。

关于java - iText - 第二次尝试生成 PDF 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10640638/

相关文章:

java - 逐行解析 2 个文件并需要避免重复(在特殊情况下)

javascript - PDF.JS 更改页面部分

java - pdfbox - 签名横向文件错误

image - JavaFX 将 WritableImage 转换为 Image

java - itext7 中 Chunk.NEWLINE 的替代品是什么

java - JPA/EclipseLink 和向后兼容的枚举映射

java - 如何静默编译Java文件除非出现错误?

java - 如何即时修改 java.lang 类?

javascript - 使用 JS 或 PHP 将 html 转换为 pdf 的最快方法是什么?

c# - iTextSharp 如何将页面从横向旋转/切换为纵向