title: Itext5 document not closing properly
body: <p>The following method is made in order to scale a pdf document to a desired format :</p>
  
  <pre><code> 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 &lt;= 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();
          }
  </code></pre>
  
  <p>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, </p>
  
  <p>I get the following exception :</p>
  
  <pre><code>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.&lt;init&gt;(PdfReader.java:176)
  at com.itextpdf.text.pdf.PdfReader.&lt;init&gt;(PdfReader.java:250)
  at com.itextpdf.text.pdf.PdfReader.&lt;init&gt;(PdfReader.java:240)
  at be.fgov.minfin.taxi.facade.docx.utils.PdfHelper.scalePDF(PdfHelper.java:370)
  </code></pre>
  
  <p>However, when i move the <code>document.close()</code> in the try block, i don't get that exception anymore.</p>
  
  <p>I don't understand why, as the finally block should be always treated before the return statement ?</p>