jairusgr
jairusgr

Reputation: 147

merge pdfs with zendpdf

I use zendpdf class to generate PDFs on a website an it works properly. Now I'm trying to merge different pdfs with zendpdf and have an issue that always return in a blank PDF, but without any errors. This is my code:

$pdf_merged = new ZendPdf\PdfDocument();

$pdf_1 = new ZendPdf\PdfDocument();
$pdf_1->load("public/files/invoices/pdf1.pdf");
$pdf_2 = new ZendPdf\PdfDocument();
$pdf_1->load("public/files/invoices/pdf2.pdf");

foreach ($pdf_1->pages as $page){
    $pdf_extract = clone $page;
    $pdf_merged->pages[] = $pdf_extract;
}
unset($pdf_extract);

foreach ($pdf_2->pages as $page){
    $pdf_extract = clone $page;
    $pdf_merged->pages[] = $pdf_extract;
}
unset($pdf_extract);

$pdf_merged->save("public/files/invoices/MERGED.pdf");

I've also tried to use the Extractor class, but with same result:

$pdf_merged = new ZendPdf\PdfDocument();

$pdf_1 = new ZendPdf\PdfDocument();
$pdf_1->load("public/files/invoices/pdf1.pdf");
$pdf_2 = new ZendPdf\PdfDocument();
$pdf_1->load("public/files/invoices/pdf2.pdf");
$extractor = new ZendPdf\Resource\Extractor();

foreach ($pdf_1->pages as $page){
    $pdf_extract = $extractor->clonePage($page);
    $pdf_merged->pages[] = $pdf_extract;
}
unset($pdf_extract);

foreach ($pdf_2->pages as $page){
    $pdf_extract = $extractor->clonePage($page);
    $pdf_merged->pages[] = $pdf_extract;
}
unset($pdf_extract);

$pdf_merged->save("public/files/invoices/MERGED.pdf");

I've made some research (here and in zf2 manual) and apparently this solution should work, but it doesn't in my case.

Could it be a problem of PDF versions?

Tahnks in advance

Upvotes: 4

Views: 898

Answers (2)

Greco Jonathan
Greco Jonathan

Reputation: 2524

Even if the PHP approach is nice to merge a PDF file there is a lot of inconvenients (library not maintained anymore, bugs, issues relative to PHP itself, performances...)

I give up PHP alternative to use PDFUNITE.

This one is able to merge more than 5000 thousand PDF files(invoices in my production environnement) in less than 0.20 seconds. After that I couldn't go back to PHP.

Upvotes: 0

Wilt
Wilt

Reputation: 44326

What I know is that there are issues with pdfs larger then 5MB. Check the issue here on GitHub.

Not sure if what you are facing is the same problem. Did you try with smaller files?

According to the answers on GitHub the module is "no longer maintained".
I am still looking for alternatives...

EDIT

ZendPdf\PdfDocument::load is a static method. You can do like this:

use ZendPdf\PdfDocument;

...

$pdf_1 = PdfDocument::load("public/files/invoices/pdf1.pdf");
$pdf_2 = PdfDocument::load("public/files/invoices/pdf2.pdf");

Upvotes: 2

Related Questions