hanneskod / libmergepdf

PHP library for merging multiple PDFs
390 stars 77 forks source link

Pages are overwritten after merging PDFs with more than 50 pages #81

Closed davidhirtz closed 1 year ago

davidhirtz commented 1 year ago

After exactly 50 merged pages the Merger suddenly starts to override the leading pages. I wrote a little test script to make sure that this is not caused by anything else.

The following loop generates two PDF files per iteration:

  1. A single page PDF (in my example generated by Dompdf, but this happens with all PDFs)
  2. A combined PDF, which merges the single page PDF to the previous stack.
$basePath = "/";

for ($page = 1; $page <= 100; $page++) {
    $dompdf = new Dompdf();
    $dompdf->setPaper('letter', 'landscape');
    $dompdf->loadHtml("<h1>Page $page</h1>");
    $dompdf->render();

    $output = $dompdf->output();

    $filename = "$basePath/page-$page.pdf";
    file_put_contents($filename, $output);

    if ($page > 1) {
        $merger = new Fpdi2Driver();
        $output = $merger->merge(
            new FileSource("$basePath/merged-" . ($page - 1) . ".pdf"),
            new FileSource($filename),
        );
    }

    $filename = "$basePath/merged-$page.pdf";
    file_put_contents($filename, $output);
}

In the end I have 100 x page-{$page}.pdf and 100 x merged-{$page}.pdf files. And until merged-50.pdf the merge works, the PDF has 50 pages from 1-50. But in merged-51.pdf the first two pages are blank/white and the first content is visible on page 3 (correctly printing out "Page 3"). Every iteration removes the content from another page, so that the final file merged-100.pdf has 50 empty pages and the first page with the content is page 51.

Any idea by what this is caused? The file size of merged PDF doesn't seem to change it, neither is the content... I'm totally lost here.

Thank you for your help!

davidhirtz commented 1 year ago

After additional tests I think this is an issue with the setasign/fpdi package, see https://github.com/Setasign/FPDI/issues/181