so after browsing through many packages like TCPDF, FPDP, DOM2PDF and many other excellent php pdf packages, I couldn't find this feature in any packages where it allows to split the pdf file by page range. for example I want to split the pdf from page 20-100 or 30-50. or create a pdf from a pdf ranging from page 20-100. so is there any library that has this feature ?
4 Answers
PDFMerger has this functionality, and I personally enjoy its simplicity.
$pdf = new PDFMerger;
$pdf->addPDF('pdf1.pdf','20-100');
$pdf->addPDF('pdf2.pdf','30-50');
$pdf->merge(); // output PDF, you can specify additional parameters here
-
1You should use a native version of FPDI because the linked PDFMerger class uses an outdated version from 2009! It's not that hard to build a simliar logic with only FPDI. Apr 13, 2015 at 18:48
-
I simply changed the FPDI file it references to the latest version and managed to get it working. Apr 13, 2015 at 18:50
If any other has problems with the pdf version > 1.4 and you want to split the pdf avoid using FPDI or any other php library you can use the below option that works perfect:
https://www.ubuntubuzz.com/2016/01/how-to-split-pdf-with-pdfseparate.html
it is a very simple command line
Split All Pages
pdfseparate <source_pdf_file> <name>-%d.pdf
Split Selected Pages Only
pdfseparate -f 1 -l 3 <source_pdf_file> <name>-%d.pdf
Split First Page Only
pdfseparate -f 1 -l 1 <source_pdf_file> <name>-%d.pdf
Split Last Page Only
pdfseparate -f 8 -l 8 <source_pdf_file> <name>-%d.pdf
I have tested the command in my local environment using homestead vagrant and in prouction environment with ubuntu 18,16. Works fine and better than gs (ghost script).
<?php
use setasign\Fpdi\Fpdi;
function split_pdf($filename, $end_directory = false)
{
$filename='backup_folderinfocommpunjab_2009/'.$file;
$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?
$new_pdf = new Fpdi();
$new_pdf->setSourceFile($filename);
// Split each page into a new PDF
// 3 and 4 is the page no as exp 3 is staring page number and 5 is last page no
for ($i = 3; $i <= 5; $i++) {
$new_pdf->AddPage();
$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";
}
}
// Create and check permissions on end directory!
split_pdf("filename.pdf", 'split/');
?>