The thing is that I am doing a code review of a large code base and I see that developpers forgot to close the PDPageContentStream in thousands of places. They only closed the PDocument.
That's way I would like to know if it is strictly necessary or not when the PDocument is closed, as the devs ask me if it is really necessary. Adding comments for the code review and having the devs fix the code could take a lot of precious time. -----Message d'origine----- De : Gilad Denneboom <gilad.denneb...@gmail.com> Envoyé : lundi 12 juin 2023 22:21 À : users@pdfbox.apache.org Objet : Re: Should I close PDPageContentStream in try-finally if I already close PDocument ? [Vous ne recevez pas souvent de courriers de gilad.denneb...@gmail.com. Découvrez pourquoi ceci est important à https://aka.ms/LearnAboutSenderIdentification ] Is there any good reason to not close it? Even if it was not strictly necessary, what's the difference in processing time? Probably negligible. On Mon, Jun 12, 2023 at 7:32 PM Masseau Olivier <olivier.mass...@inetum.com.invalid> wrote: > Hello, > > 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. > > Thanks a lot. > >