PdfBox : Should I close PDPageContentStream if I already close PDocument?

67 Views Asked by At

Let's say I have this which creates a new Pdf document and adds content to it:

public static void createPdfDocumentAndAddContent() throws Exception {
    PDDocument document = null;
    PDPageContentStream contentStream = null;

    try {
        document = new PDDocument();
        PDPage page = new PDPage();
        document.addPage(page);
        
        contentStream = new PDPageContentStream(document, page);

        contentStream.setFont(PDType1Font.COURIER, 12);
        contentStream.beginText();
        contentStream.showText("Hello World");
        contentStream.endText();
        contentStream.close();
        
        // ...

        document.save("pdfBoxHelloWorld.pdf");
        document.close();
    } finally {
        // Necessary to handle exceptions
        IOUtils.closeQuietly(contentStream); // In case an exception occurs, do I really need this or closing the document is enough ?
        IOUtils.closeQuietly(document);
    }
}

Do I really need to close the content stream in the finally block or closing the document is enough ?

From all the examples I see online it is hard to tell as 99% of the examples do not care about potential errors.

The rare examples I see where they handle errors, only the document is closed. But the content stream being a Closeable for me it also needs to be closed, not knowing what exactly document.close() does and if it is enough.

0

There are 0 best solutions below