Search code examples
phpcakephppdfmergepage-numbering

PHP Insert multiple PDF's into PDF on specific page number


My problem is - A user can upload a PDF-File and now I want to add other (between 1 and n) single page PDF's after every Page of the user uploaded PDF.

For example a user uploads a PDF with 4 Pages and I have got 3 single page PDF's on my Webserver that I want to merge with the user PDF. The resulting PDF should then look like this:

Page 1: Page #1 from User uploaded PDF

Page 2: First Single-Page-PDF from Webserver

Page 3: Page #2 from User uploaded PDF

Page 4: Second Single-Page-PDF from Webserver

Page 5: Page #3 from User uploaded PDF

Page 6: Third Single-Page-PDF from Webserver

Page 7: Page #4 from User uploaded PDF

Page 8: First Single-Page-PDF from Webserver

So far I've tried it with PDFMerger

$pdf = new PDFMerger;

$pdf->addPDF('samplepdfs/userpdf.pdf', 'all')
    ->addPDF('samplepdfs/one.pdf', 'all')
    ->addPDF('samplepdfs/two.pdf', 'all')
    ->addPDF('samplepdfs/three.pdf', 'all')
    ->merge('file', 'xxx/result.pdf');

but this only adds the other PDF's at the end.. Is there a solution in PHP where I can specify the number of the page where the other PDF's shall be inserted?


Solution

  • You should avoid using the PDFMerger class. It is almost 6 (!!!) years old! You can do the same with FPDI without much effort. Anyhow you should insert the pages in the order you want them to appear. So I guess it's more a logic problem. From what you'd written in your question I assume that you want to import a whole document while spreading another document with 3 pages between the imported pages. So a simple POC could look like this:

    <?php
    
    require_once("libs/fpdf/fpdf.php");
    require_once("libs/fpdi/fpdi.php");
    
    $pdf = new FPDI();
    
    // let's prepare the static "filler pages"
    $staticIds = array();
    $pageCount = $pdf->setSourceFile('pdf/on/the/webserver.pdf');
    for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
        $staticIds[$pageNumber] = $pdf->importPage($pageNumber);
    }
    
    // get the page count of the uploaded file
    $pageCount = $pdf->setSourceFile('the/uploaded.pdf');
    // let's track the page number for the filler page
    $fillerPageCount = 1;
    // import the uploaded document page by page
    for ($pageNumber = 1; $pageNumber <= $pageCount; $pageNumber++) {
        $tplId = $pdf->importPage($pageNumber);
        $pdf->AddPage();
        $pdf->useTemplate($tplId, null, null, 0, 0, true);
    
        // add the current filler page
        $pdf->AddPage();
        $pdf->useTemplate($staticIds[$fillerPageCount], null, null, 0, 0, true);
    
        // update the filler page number or reset it
        $fillerPageCount++;
        if ($fillerPageCount > count($staticIds)) {
            $fillerPageCount = 1;
        }
    }
    
    // done
    $pdf->Output('xxx/result.pdf', 'F');