gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:13:58 27 4
gpt4 key购买 nike

我有一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com