我有一個使用iText從結果集生成PDF的Java桌面應用程序。您第一次生成PDF時,它工作正常。當您嘗試生成第二個問題時,問題就來了。它拋出一個DocumentException,說文檔已關閉。我試圖找到其他人有這個問題的例子,我想出了很少,這導致我相信我犯了一個非常簡單的錯誤,我找不到它。iText - 第二次嘗試生成PDF時失敗
下面的代碼是調用報表類的事件處理程序的一個片段:
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類在實例化時創建一個新線程。所以我馬上就回到了我剛開始的時候,仍然停滯不前。
請編輯您的代碼:正確縮進,並將其縮小爲一個重現錯誤的最小示例。另外,請提及哪一行會引發異常。 –