java - 当 Document 对象打开时,获取 "java.lang.RuntimeException: The document is not open"

标签 java pdf itext runtimeexception pdf-writer

我正在尝试向我的 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();
    }//

    //...
}

这里的调试结果告诉我文档输入和临时文件都已打开。我添加到代码中另一个位置的调试确认这是我们正在使用的开放文档变量。

最佳答案

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

关于java - 当 Document 对象打开时,获取 "java.lang.RuntimeException: The document is not open",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57777336/

相关文章:

java - JPA 条件查询 : fields of the object doesn't mapped

java - 我如何获得用户音乐目录?

c# - 将 PDF 读入字符串或字节 [] 并将该字符串/字节 [] 写回磁盘

java - 如何在 iText 中定位表格

java - 如何在使用 iText 创建的 PDF 中显示阿拉伯语

java - 通过删除清除所有项目后列表返回一项

java - 在数据结构中查找最大值最小值和最大键的值

javascript - 嵌入 PDF,无需工具栏和滚动条。为什么这不起作用?

javascript - 如何使用js创建西里尔文PDF

java - IText 将 pdf 中的标题居中