Search code examples
phppdftcpdffpdi

Php Remove page from existing pdf file


What is the easiest way to remove one page (ie. the last page) from a local pdf file using php? I have around 100 files, and each one needs to have its last page dropped. Optimally, I want to replace the file with a file of the same name that is just one page shorter.


Solution

  • You can use FPDI

    Example:

    pdf = new FPDI();
    $pageCount = $pdf->setSourceFile('document.pdf');
    
    //  Array of pages to skip -- modify this to fit your needs
    $skipPages = [3,15,17,22];
    
    //  Add all pages of source to new document
    for( $pageNo=1; $pageNo<=$pageCount; $pageNo++ )
    {
        //  Skip undesired pages
        if( in_array($pageNo,$skipPages) )
            continue;
    
        //  Add page to the document
        $templateID = $pdf->importPage($pageNo);
        $pdf->getTemplateSize($templateID);
        $pdf->addPage();
        $pdf->useTemplate($templateID);
    }
    
    $pdf->Output();
    

    You can delete de last page using the array size easily.