0

The following method is made in order to scale a pdf document to a desired format :

 Document document = new Document(MarginsPDFHelper.DIM_PAGE, MarginsPDFHelper.MARGIN_GEN, MarginsPDFHelper.MARGIN_GEN, MarginsPDFHelper.MARGIN_TOP, MarginsPDFHelper.MARGIN_BOT);
    try {
        PdfReader reader = new PdfReader(pdfByte);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();
        PdfContentByte content = writer.getDirectContent();
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(reader, i);
            Rectangle pageSize = reader.getPageSizeWithRotation(i);
            float scaleX = MarginsPDFHelper.DIM_PAGE.getWidth() / pageSize.getWidth();
            float scaleY = MarginsPDFHelper.DIM_PAGE.getHeight() / pageSize.getHeight();
            float scale = Math.min(scaleX, scaleY);
            content.addTemplate(page, scale, 0, 0, scale, 0, 0);
        }
        return outputStream.toByteArray();
    } catch (Exception e) {
        LOGGER.error("Can not scale pdf", e);
    } finally {
        if (document.isOpen()) {
            document.close();
        }

The problem that i'm confronted to is that the object com.itextpdf.text.Document is closed in the finally block and that way, it seems that it's not closed properly,

I get the following exception :

Caused by: com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found.
at com.itextpdf.text.pdf.PRTokeniser.getHeaderOffset(PRTokeniser.java:227)
at com.itextpdf.text.pdf.PdfReader.getOffsetTokeniser(PdfReader.java:486)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:176)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:250)
at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:240)
at be.fgov.minfin.taxi.facade.docx.utils.PdfHelper.scalePDF(PdfHelper.java:370)

However, when i move the document.close() in the try block, i don't get that exception anymore.

I don't understand why, as the finally block should be always treated before the return statement ?

Ramzi G.
  • 59
  • 1
  • 10
  • 1
    *"I don't understand why, as the finally block should be always treated before the return statement ?"* - No. The `finally` block is executed when execution leaves the `try` block. In particular the calculation of the expression of the `return` statement still happens _inside_ the `try` block, i.e. _before_ the `finally` block. – mkl Feb 21 '19 at 15:20
  • 1
    Thanks mkl, I get it now. – Ramzi G. Feb 21 '19 at 18:07

1 Answers1

1

The finally block always executes when the try block exits. 1

André Lemos
  • 837
  • 6
  • 18
  • 3
    You might want to explain what that means in the context of the OP's code. I doubt the sentence as is helps him at all. – mkl Feb 21 '19 at 15:16