title: iText7: Error at file pointer when merging two pdfs
body: <p>We are in the last steps of evaluating iText7. We use iText 7.1.0 and html2pdf 2.0.0.</p>
  
  <p>What we do: we send a json_encoded collection with pdf-data (which includes html for header, body and footer) to our Java app. There we iterate over the collection, create a byteArrayOutputStream for each pdf-data element and merge them together. We then send the results to a script which echoes it to e.g. a browser. Although the pdf is displayed correctly, we encounter errors while creating it: </p>
  
  <pre><code>    com.itextpdf.io.IOException: Error at file pointer 226,416.
      ...
      Caused by: com.itextpdf.io.IOException: xref subsection not found.
      ... 73 common frames omitted
  </code></pre>
  
  <p>If we create only one part of the collection, no error is thrown. </p>
  
  <p>Iterate over collection and merge:</p>
  
  <pre><code>@RequestMapping(value = "/pdf", method = RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE)
  public byte[] index(@RequestBody PDFDataModelCollection elements, Model model) throws IOException {    
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      PdfWriter writer = new PdfWriter(byteArrayOutputStream);
      try (PdfDocument resultDoc = new PdfDocument(writer)) {
          for (PDFDataModel pdfDataModel : elements.getElements()) {
              PdfReader reader = new PdfReader(new ByteArrayInputStream(creationService.createDatasheet(pdfDataModel)));
              try (PdfDocument sourceDoc = new PdfDocument(reader)) {
                  int n = sourceDoc.getNumberOfPages(); //&lt;-- IOException on second iteration
                  for (int i = 1; i &lt;= n; i++) {
                      PdfPage page = sourceDoc.getPage(i).copyTo(resultDoc);
                      resultDoc.addPage(page);
                  }
              }
          }
      }
      return byteArrayOutputStream.toByteArray(); //outputs the final pdf
  }
  </code></pre>
  
  <p>Creation of part:</p>
  
  <pre><code>public byte[] createDatasheet(PDFDataModel pdfDataModel) throws IOException {
      PdfWriter writer = new PdfWriter(byteArrayOutputStream);
  
      //Initialize PDF document
      PdfDocument pdfDoc = new PdfDocument(writer);
  
      try (
          Document document = new Document(pdfDoc)
      ) {
  
          //header, footer, etc
  
          //body
          for (IElement element : HtmlConverter.convertToElements(pdfDataModel.getBody(), this.props)) {
              document.add((IBlockElement) element);
          }
  
          footer.writeTotalNumberOnPages(pdfDoc);
      }
  
      return byteArrayOutputStream.toByteArray();
  }
  </code></pre>
  
  <p>We are grateful for any suggestion.</p>