Skip to content

Instantly share code, notes, and snippets.

@odan
Last active March 25, 2023 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save odan/7e1fc4a166d02cb643fb800089d7aa3c to your computer and use it in GitHub Desktop.
Save odan/7e1fc4a166d02cb643fb800089d7aa3c to your computer and use it in GitHub Desktop.
Spliting a PDF file into multiple PDF files

Spliting a PDF file into multiple PDF files

This function extracts all of the pages from a larger PDF file into single-page PDF files.

Installation

composer require setasign/fpdi-fpdf

Code

use setasign\Fpdi\Fpdi;

/**
 * Split all of the pages from a larger PDF file into single-page PDF files.
 *
 * @param string $filename The filename of the PDF to split
 * @param string $directory The output directory for the new PDF files
 *
 * @return void
 */
function split_pdf(string $filename, string $directory)
{
    $pdf = new FPDI();
    $pageCount = $pdf->setSourceFile($filename);
    $file = pathinfo($filename, PATHINFO_FILENAME);

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

        $newFilename = sprintf('%s/%s_%s.pdf', $directory, $file, $i);
        $newPdf->Output($newFilename, 'F');
    }
}

Usage

split_pdf('test.pdf', 'split/');

Keywords: PDF, PHP, FPDI, FPDF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment