Search code examples
phppdfpdf-generationfpdffpdi

links (hyperlink) inside pdf is removed when splitting multiple page pdf into different single page


i was splitting pdf into different single page using fpdf and fpdi. Everything works fine but the link inside pdf was not working. Link was removed on splitted single pages.

split_pdf("test.pdf", 'splitedpdf/');

function split_pdf($filename, $end_directory = false)
{
    require_once('fpdf/fpdf.php');
    require_once('fpdi/fpdi.php');

    $end_directory = $end_directory ? $end_directory : './';
    $new_path = preg_replace('/[\/]+/', '/', $end_directory.'/'.substr($filename, 0, strrpos($filename, '/')));

    if (!is_dir($new_path))
    {
        // Will make directories under end directory that don't exist
        // Provided that end directory exists and has the right permissions
        mkdir($new_path, 0777, true);
    }

    $pdf = new FPDI();
    $pagecount = $pdf->setSourceFile($filename); // How many pages?

    // Split each page into a new PDF
    for ($i = 1; $i <= $pagecount; $i++) {
        $new_pdf = new FPDI();
        $new_pdf->AddPage();
        $new_pdf->setSourceFile($filename);
        $new_pdf->useTemplate($new_pdf->importPage($i));

        try {
            $new_filename = $end_directory.str_replace('.pdf', '', $filename).'_'.$i.".pdf";
            $new_pdf->Output($new_filename, "F");
            echo "Page ".$i." split into ".$new_filename."<br />\n";
        } catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }
    }
    //  $pdf->close();
}

Solution

  • FPDI is not able to handle any dynamic content link links, form fields or any other annotation type. There's an extension which support at least links (only compatible with FPDI 1.4.4 + FPDF_TPL 1.2.3).

    If you need to extract the pages including all attached annotations, you may check out the SetaPDF-Merger component (not free!).