How can I resolve the error saying Document was closed using iText 7.1.6?
Asked Answered
M

1

1

I am using iText 7.1.6 to generate the PDF. When I try to run , I get this error document was closed . It is impossible to execute the action.

I checked solutions on Stack Overflow for this, but they are saying it is related to fonts. I modified the fonts by creating instance every time I use it, but even then I get same issue.

How can I resolve this issue?

Please find the below code and exception:

Document doc = null;
PdfPage sourcePage = null;
try (InputStream resource = new FileInputStream(new File(Paths.get("Output").toAbsolutePath()+"/source.pdf"));
     PdfReader pdfReader = new PdfReader(resource);
     PdfDocument pdfDocument = new PdfDocument(pdfReader)) {

    PdfDocumentContentParser contentParser = new PdfDocumentContentParser(pdfDocument);
    MarginFinder strategy = contentParser.processContent(1, new MarginFinder());

    sourcePage = pdfDocument.getPage(1);
    sourcePage.setCropBox(strategy.getBoundingBox());
    sourcePage.setMediaBox(strategy.getBoundingBox());
}


@SuppressWarnings("resource")
PdfWriter writer = new PdfWriter(new FileOutputStream(new File(Paths.get("Output").toAbsolutePath()+"/final.pdf"))).setSmartMode(true);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.setDefaultPageSize(PageSize.A3.rotate());
String fonts[] = {Paths.get("fonts").toAbsolutePath() + "/TREBUC.TTF", Paths.get("fonts").toAbsolutePath() + "/TREBUCBD.TTF", Paths.get("fonts").toAbsolutePath() + "/TREBUCBI.TTF",Paths.get("fonts").toAbsolutePath() + "/TREBUCIT.TTF"};
FontProvider fontProvider = new FontProvider();
Map<String, PdfFont> pdfFontMap = new HashMap<String, PdfFont>();
for (String font : fonts) {
    FontProgram fontProgram = FontProgramFactory.createFont(font);
    if (font.endsWith("TREBUC.TTF")) {
        pdfFontMap.put("NORMAL", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
    } else if (font.endsWith("TREBUCBD.TTF")) {
        pdfFontMap.put("BOLD", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
    } else if (font.endsWith("TREBUCBI.TTF")) {
        pdfFontMap.put("BOLD_ITALIC", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
    } else if (font.endsWith("TREBUCIT.TTF")) {
        pdfFontMap.put("ITALIC", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
    }

    fontProvider.addFont(fontProgram);
}

TestVisualSummaryNew testVisualSummaryNew = new TestVisualSummaryNew();
NormalPageHeader headerHandler = testVisualSummaryNew.new NormalPageHeader(Paths.get("images").toAbsolutePath() + "\\logo.png", pdfFontMap);
pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
PageEndEvent pageEndEvent = testVisualSummaryNew.new PageEndEvent(Paths.get("images").toAbsolutePath() + "\\FooterLineExternal.png" ,pdfFontMap);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, pageEndEvent);

doc = new Document(pdfDoc);
doc.setTopMargin(55);
PdfFormXObject xobject = sourcePage.copyAsFormXObject(pdfDoc);
Rectangle xobjectBoundaryBox = xobject.getBBox().toRectangle();
xobject.getPdfObject().put(PdfName.Matrix, new PdfArray(new float[] {1, 0, 0, 1, -xobjectBoundaryBox.getLeft(), -xobjectBoundaryBox.getBottom()}));
Image image = new Image(xobject);
image.setAutoScale(true);
doc.add(image);
System.out.println("Converted to PDF Succesfully >>> source.pdf");

Exception

com.itextpdf.kernel.PdfException: Document was closed. It is
impossible to execute action. at
com.itextpdf.kernel.pdf.PdfDocument.checkClosingStatus(PdfDocument.java:2041)
at
com.itextpdf.kernel.pdf.PdfDocument.getWriter(PdfDocument.java:706)
at
com.itextpdf.kernel.pdf.PdfIndirectReference.getWriter(PdfIndirectReference.java:270)
at com.itextpdf.kernel.pdf.PdfObject.copyTo(PdfObject.java:318) at
com.itextpdf.kernel.pdf.PdfPage.copyAsFormXObject(PdfPage.java:439)

Modiste answered 13/6, 2019 at 6:23 Comment(3)
You are copying the page from the original document (sourcePage.copyAsFormXObject), after this original document is closed. After document closing you cannot perform any operations with it.Finch
Hi, Thanks for the update. For testing purpose, I have removed the code wherever the documents are getting closed and tested. Even then, I get the same error. Can you please support ?Modiste
"I have removed the code wherever the documents are getting closed" - See my answer, it doesn't suffice to remove the pdfDocument.close() line, you also have to move the pdfDocument = new PdfDocument(pdfReader) out of the try-with-resources resources as those resources also are closed at the end of the try block.Siracusa
S
2

As already indicated in comment to your previous question

You appear to already have closed the source document at that time. It mustn't be closed then to allow copying from it.

Thus, don't close it early, neither explicitly nor by creating it in a try-with-resources:

Document doc = null;
PdfDocument pdfDocument = null; //!!!
PdfPage sourcePage = null;
try (   InputStream resource = new FileInputStream(new File(Paths.get("Output").toAbsolutePath()+"/test.pdf"));    ) {  //!!!
   PdfReader pdfReader = new PdfReader(resource); //!!!
   pdfDocument = new PdfDocument(pdfReader); //!!!
   PdfDocumentContentParser contentParser = new PdfDocumentContentParser(pdfDocument);
   MarginFinder strategy = contentParser.processContent(1, new MarginFinder());

   sourcePage = pdfDocument.getPage(1);
   sourcePage.setCropBox(strategy.getBoundingBox());
   sourcePage.setMediaBox(strategy.getBoundingBox());
   //pdfDocument.close(); //!!!
}


try {
   @SuppressWarnings("resource")
   PdfWriter writer = new PdfWriter(new FileOutputStream(new File(Paths.get("Output").toAbsolutePath()+"/final.pdf"))).setSmartMode(true);
   PdfDocument pdfDoc = new PdfDocument(writer);
   pdfDoc.setDefaultPageSize(PageSize.A3.rotate());
   String fonts[] = {Paths.get("fonts").toAbsolutePath() + "/TREBUC.TTF", Paths.get("fonts").toAbsolutePath() + "/TREBUCBD.TTF", Paths.get("fonts").toAbsolutePath() + "/TREBUCBI.TTF",Paths.get("fonts").toAbsolutePath() + "/TREBUCIT.TTF"};
   FontProvider fontProvider = new FontProvider();
   Map<String, PdfFont> pdfFontMap = new HashMap<String, PdfFont>();
   for (String font : fonts) {
       FontProgram fontProgram = FontProgramFactory.createFont(font);
       if (font.endsWith("TREBUC.TTF")) {
           pdfFontMap.put("NORMAL", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
       } else if (font.endsWith("TREBUCBD.TTF")) {
           pdfFontMap.put("BOLD", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
       } else if (font.endsWith("TREBUCBI.TTF")) {
           pdfFontMap.put("BOLD_ITALIC", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
       } else if (font.endsWith("TREBUCIT.TTF")) {
           pdfFontMap.put("ITALIC", PdfFontFactory.createFont(fontProgram, PdfEncodings.WINANSI, true));
       }

       fontProvider.addFont(fontProgram);
   }

   TestVisualSummaryNew testVisualSummaryNew = new TestVisualSummaryNew();
   NormalPageHeader headerHandler = testVisualSummaryNew.new NormalPageHeader(Paths.get("images").toAbsolutePath() + "\\logo.png", pdfFontMap);
   pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
   PageEndEvent pageEndEvent = testVisualSummaryNew.new PageEndEvent(Paths.get("images").toAbsolutePath() + "\\FooterLineExternal.png" ,pdfFontMap);
   pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, pageEndEvent);

   doc = new Document(pdfDoc);
   doc.setTopMargin(55);
   PdfFormXObject xobject = sourcePage.copyAsFormXObject(pdfDoc);
   Rectangle xobjectBoundaryBox = xobject.getBBox().toRectangle();
   xobject.getPdfObject().put(PdfName.Matrix, new PdfArray(new float[] {1, 0, 0, 1, -xobjectBoundaryBox.getLeft(), -xobjectBoundaryBox.getBottom()}));
   Image image = new Image(xobject);
   image.setAutoScale(true);
   doc.add(image);
   pdfDoc.close();
   doc.close();
   System.out.println("Converted to PDF Succesfully >>> convertedSvg_" + uuid + ".pdf");
} catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error Occured while converting to PDF = " + e.getMessage());
}

pdfDocument.close();  //!!!
Siracusa answered 13/6, 2019 at 10:32 Comment(5)
Hi, Appreciate your support. Thank you. As suggested by you, I did change the code which explicitly was used to close the document. In Addition, I removed the try-catch block for testing purpose. Looks like there is same issue. I have updated the code above. Can you please have a look at it once ?Modiste
@Modiste I the code from my answer and merely did the obvious replacements (I don't have files where you do). It runs without issue.Siracusa
@Modiste I had a look at the code in your question and you did not apply all the changes I asked you to do. In particular pdfReader and pdfDocument are still created as resources in a try-with-resources block. Thus, they are closed at the end of the block, long before you try to import the page.Siracusa
@Modiste You can use that try-with-resources construct if you call the later code from within that block, cf. my example code referred to in my answer to your previous question. You on the other hand don't call it from within but thereafter. Thus, you must not use try-with-resources like that.Siracusa
Thank you very much for your kind support. The issue got fixed ! :)Modiste

© 2022 - 2024 — McMap. All rights reserved.