As requirement for one of my projects, I needed to concatenate multipe PDF files provided by the user into just one file.
To achieve this, we need the TCPDF and FPDI libraries.
Class to concatenate pdf, Pdf_concat.class.php:
require_once('./includes/tcpdf/config/lang/eng.php'); require_once('./includes/tcpdf/tcpdf.php'); require_once('./includes/fpdi/fpdi.php'); class Pdf_concat extends FPDI { var $files = array(); function setFiles($files) { $this->files = $files; } function concat() { foreach($this->files AS $file) { $pagecount = $this->setSourceFile($file); for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $this->ImportPage($i); $s = $this->getTemplatesize($tplidx); $this->AddPage('P', array($s['w'], $s['h'])); $this->useTemplate($tplidx); } } } }
Usage:
$file2merge=array('file1.pdf', 'folder/file2.pdf', file3.pdf); $pdf = new Pdf_concat(); $pdf->setFiles($file2merge); $pdf->concat(); $pdf->Output('folder/newfile.pdf', "I");
$pdf->Output(“newpdf.pdf”, “I”) shows the merged file on screen.
After this I recommend to you to keep the file already merged in the server, then you will not need to generate it another time. To do this you can use $pdf->Output(“newpdf.pdf”, “F”); instead and save the file.
Latest posts by Abhishek Gupta (see all)
- PHP syntactic sugar code example - September 5, 2021
- Python convert random string date format to Datetime - July 12, 2021
- Laravel Custom Exception Handlers - March 28, 2019
There is a syntax error on line 14. Could you update the code?
Fixed. Thanks for pointing out.
Thanks for the solution but in the merged pdf a black line appears at top and bottom of each page,any idea why that appears??
I got the fix for that,need to set the Header and footer to false in the beginning of the concat function
$this->setPrintHeader(false);
$this->setPrintFooter(false);
Cheers
Thanks Nisar, I guess it saved me a lot of research because I run in the same problem! 🙂
This function doesn’t preserve the anchor links in the PDF.