Tech Tip: Merging PDF's with PHP
PRODUCT: 4D | VERSION: 12.1 | PLATFORM: Mac & Win
Published On: March 24, 2011
If you have multiple PDF's and you want to merge them together into one document there is already a PHP library out there for that. You can use the PDF Merger for PHP.
4D v12 offers an included in PHP interpreter which allows developers to take advantage of code such as this. First, download the PDF Merger library from https://pdfmerger.codeplex.com/. Then install the PDF Merger folder in your database's Resources folder. In the example below there is a folder named "PDFMerger" in the Resources folder.
Once you have this setup create a PHP file which can run the PDF Merger code. Below is the sample used in this Tech Tip:
include 'PDFMerger.php'; function mergepdfs ($output_pdf = 'samplepdfs/aa_TEST.pdf') { $numArgs = func_num_args(); if($numArgs >= 2) { $pdf = new PDFMerger; for ($i = 2; $i <= $numArgs; $i++) { $pdf->addPDF(func_get_arg($i-1), 'all'); } $pdf->merge('file', $output_pdf); return "success"; } else { return "no PDF docs passed"; } } |
Once you have this file (named "mypdfmerger.php") in the PDFMerger folder then you can call it from 4D. Here is the code used to call this script:
C_TEXT($scriptPath;$functionName;$phpResult;$resultPDF;$pdf1;$pdf2) C_BOOLEAN($err) $scriptPath:=Get 4D folder(Current Resources folder)+"PDFMerger\\mypdfmerger.php" $functionName:="mergepdfs" $resultPDF:="samplepdfs\tomtestPDF.pdf" $pdf1:="samplepdfs\\one.pdf" $pdf2:="samplepdfs\\two.pdf" $err:=PHP Execute($scriptPath;$functionName;$phpResult;$resultPDF;$pdf1;$pdf2) |
You call PHP Execute and pass the path to the script you are calling ("mypdfmerger.php"), the function name in that script ("mergepdfs"), a return value for the result, and then the parameters that the function takes. In this case the first parameter is the path to the final PDF, then the path to each PDF to merge. In the sample two PDF's in the "samplepdfs" folder are merged into one. The script can handle one plus PDF's and merge them.
$pdf->addPDF(func_get_arg($i-1), 'all');
->addPDF(func_get_arg(1), 'all');
->addPDF(func_get_arg(2), 'all');
->merge('file', $output_pdf);
So I used multiple if statements up to the maximum number of parameters I expected to be passed. If 3 parameters I merged 2 documents, if 4 I merged 3 documents, etc.
if (count($args) == 3) {
$pdf->addPDF(func_get_arg(1), 'all')
->addPDF(func_get_arg(2), 'all')
->merge('file', func_get_arg(0));
}
if (count($args) == 4) {
$pdf->addPDF(func_get_arg(1), 'all')
->addPDF(func_get_arg(2), 'all')
->addPDF(func_get_arg(3), 'all')
->merge('file', func_get_arg(0));
}
Also I could not get fun_num_args() to work so I used $args = func_get_args(); instead and counted the elements in the $args array.
Finally $err always returns false in the 4D code. So I reverted to testing that the merged document existed to confirm that the merged worked instead of testing the function result.