获得;java.lang.RuntimeException:文档未打开";,打开文档对象时

获得;java.lang.RuntimeException:文档未打开";,打开文档对象时,java,pdf,itext,runtimeexception,pdf-writer,Java,Pdf,Itext,Runtimeexception,Pdf Writer,我正在尝试将页码/页数添加到我的PDF中。我们这样做的方式是创建报告的第二个副本以获取页面计数,然后迭代该循环以将数字写回第一个报告。报告已成功运行,但未添加页码。快速查看日志,我发现一个RuntimeException,表示文档未从以下代码打开: public void addPageCount(String jsonData, Document input, String fileLocation, String tempFileLocation, float xPos, float yPo

我正在尝试将页码/页数添加到我的PDF中。我们这样做的方式是创建报告的第二个副本以获取页面计数,然后迭代该循环以将数字写回第一个报告。报告已成功运行,但未添加页码。快速查看日志,我发现一个RuntimeException,表示文档未从以下代码打开:

public void addPageCount(String jsonData, Document input, String fileLocation, String tempFileLocation, float xPos, float yPos, float rotation)
        throws FileNotFoundException, IOException, DocumentException, SQLException {
    String tempFileSpot1 = tempFileLocation + "temp1.pdf";
    Document temp = new Document();
    FileOutputStream fos = new FileOutputStream(tempFileSpot1);
    temp.open();
    PdfWriter writer;
    boolean leaveOpen = input.isOpen();
    if (!input.isOpen()) {
        input.open();
    }
    try {
        writer = PdfWriter.getInstance(temp, fos);
    }//try
    catch (DocumentException e) {
        e.printStackTrace();
        throw e;
    }//catch (DocumentException)

    System.out.println("temp.isOpen = " + temp.isOpen());
    System.out.println("input.isOpen = " + input.isOpen());
    try {
        this.makePDF(jsonData, temp, writer);
        //...
    } catch (Exception e5) {
        e5.printStackTrace();
    }//

    //...
}

这里的调试结果告诉我,文档输入和temp都是打开的。我添加到代码中另一个点的调试确认这是我们正在处理的一个打开的文档变量。

这里的问题是,虽然来自I-Text的错误消息说文档未打开,但实际上是PdfWriter未打开。添加
writer.open()在try/catch块中的构造函数修复此问题后。

听起来可能值得提交一个快速PR over-请参阅Itext,它希望您在打开文档(
temp.open()
)之前首先将所有侦听器与文档关联(
PdfWriter.getInstance(temp,fos)
)。你用另一种方法去做,这是错误的。