javapdfitextruntimeexceptionpdf-writer

Getting "java.lang.RuntimeException: The document is not open", when the Document object is open


I am trying to add a page number/page count to my pdfs. The way that we are doing this is to create a second copy of the report to get the page count, and then iterate through that loop to write the numbers back onto the first report. The report has been sucessfully running, but the page numbers were not being added. A quick look at the logs showed that I am getting a RuntimeException, saying that the Document is not open from the following code:

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();
    }//

    //...
}

The result of the debugs here inform me that both Documents input and temp are open. The debug I added to another spot in the code confirms that this is an open Document variable that we are working with here.


Solution

  • The issue here is that while the error message from I-Text says that the Document is not open, it was really the PdfWriter that was not open. Adding writer.open(); after the constructor in the try/catch block fixed this issue.