-
-
Save starbuck93/2c9ad8f6a6d0a57f1164352c80ab0531 to your computer and use it in GitHub Desktop.
Split PDF to individual pages using FPDI and FPDF while keeping the original PDF's size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Split PDF file | |
* | |
* <p>Split all of the pages from a larger PDF files into | |
* single-page PDF files.</p> | |
* | |
* @package FPDF required http://www.fpdf.org/ | |
* @package FPDI required http://www.setasign.de/products/pdf-php-solutions/fpdi/ | |
* @param string $filename The filename of the PDF to split | |
* @param string $end_directory The end directory for split PDF (original PDF's directory by default) | |
* @return void | |
*/ | |
/*composer.json | |
{ | |
"require": { | |
"setasign/fpdi": ">1", | |
"setasign/fpdf": ">1" | |
} | |
} | |
*/ | |
require_once('vendor/autoload.php'); | |
use \setasign\Fpdi\Fpdi as FPDI; | |
function split_pdf($filename, $end_directory = false) | |
{ | |
$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? | |
$pdf->close(); | |
// Split each page into a new PDF | |
for ($i = 1; $i <= $pagecount; $i++) { | |
$new_pdf = new FPDI(); | |
$new_pdf->setSourceFile($filename); | |
$tplIdx = $new_pdf->importPage($i); | |
$size = $new_pdf->getTemplateSize($tplIdx); | |
$new_pdf->AddPage(); | |
$new_pdf->useTemplate($tplIdx,null, null, $size['width'], $size['height'], TRUE); | |
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"; | |
} | |
$new_pdf->close(); | |
} | |
} | |
// Create and check permissions on end directory! | |
split_pdf('filename.pdf', 'split/'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if your PDF version is >1.4, then use ghostscript to change the version to 1.4
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dNOPAUSE -dQUIET -dBATCH -sOutputFile=NEW_FILENAME.pdf ORIGINAL_FILENAME.pdf
https://stackoverflow.com/a/22430830/2953835