我正在使用MPDF库生成pdf文件。我在根目录中创建了两个PDF文件,如下所示:
$invoice_nos = ['0'=>'ISE-00000014Y18','1'=>'ISE-00000005Y18'];
foreach ($invoice_nos as $key => $invoice_no) {
$html = 'Invoice No - '.$invoice_no;
$pdf_file_name = $invoice_no.'.pdf';
$pdf_file_path = ROOT . '/app/webroot/Service_Invoices/'. DS .$pdf_file_name ;
ob_start();
$mpdf = new \mPDF('utf-8', 'A4' ,'','',5,5,36,10,5,4);
$mpdf->WriteHTML($html,2);
ob_clean();
$mpdf->Output($pdf_file_name,'f');
}
现在我想将这两个文件合并为一个包含不同页面的文件。我怎样才能做到这一点?我搜索过很多例子,但没有任何工作。
答案 0 :(得分:2)
mPDF不是合并PDF文件的最佳工具。使用GhostScript:
,您会感觉更好gs -dBATCH -dSAFER -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=combined.pdf invoice1.pdf invoice2.pdf
或者,将两张发票直接生成一个文件:
$invoice_nos = ['0' => 'ISE-00000014Y18', '1' => 'ISE-00000005Y18'];
$mpdf = new \mPDF('utf-8', 'A4', '', '', 5, 5, 36, 10, 5, 4);
foreach ($invoice_nos as $key => $invoice_no) {
$html = 'Invoice No - ' . $invoice_no;
$mpdf->WriteHTML($html, 2);
$mpdf->WriteHTML('<pagebreak>');
}
$pdf_file_name = $invoice_no . 'invoices.pdf';
$mpdf->Output($pdf_file_name, 'f');
答案 1 :(得分:0)
您好,所以我实际上使用此代码来展平具有可编辑表单的PDF,但我相信我们可以更改它以合并PDF格式。
此解决方案使用php的Imagick(),它应该是您托管环境的一部分。
所以这是代码,我试图尽可能地评论它。您将调用mergePdf()并将目标文件夹(您的文件所在的位置以及保存新文件的位置)和要合并的文件数组(只是名称),然后是新文件名。完成后,它会将新文件保存在目标文件夹中。
/**
* mergePdf()
*
* @param mixed $destinationPath
* @param array $files
* @param mixed $newFileName
* @return
*/
public function mergePdf($destinationPath, $files, $newFileName){
//Create array to hold images
$array_images = array();
//Loop through to be merged
foreach($files as $file){
//Firstly we check to see if the file is a PDF
if(mime_content_type($destinationPath.$file)=='application/pdf'){
// Strip document extension
$file_name = pathinfo($file, PATHINFO_FILENAME);
// Convert this document
// Each page to single image
$im = new imagick();
//Keep good resolution
$im->setResolution(175, 175);
$im->readImage($destinationPath.$file);
$im->setImageFormat('png');
$im->writeImages($destinationPath.$file_name.'.png',false);
//loop through pages and add them to array
for($i = 0; $i < $im->getNumberImages(); $i++){
//insert images into array
array_push($array_images, $destinationPath.$file_name.'-'.$i.'.png');
}
//Clear im object
$im->clear();
$im->destroy();
}else{
return false;
}
}
//Now that the array of images is created we will create the PDF
if(!empty($array_images)){
//Create new PDF document
$pdf = new Imagick($array_images);
$pdf->setImageFormat('pdf');
if($pdf->writeImages($destinationPath.$newFileName, true)){
$pdf->clear();
$pdf->destroy();
//delete images
foreach($array_images as $image){
unlink($image);
}
return true;
}else{
return false;
}
}else{
return false;
}
}
public function getMergePdf(){
$destinationPath = "/your/destination/to/the/file/goes/here/";
//put the files in the order you want them to be merged
$files = array('file1.pdf','file2.pdf','file3.pdf');
$this->mergePdf($destinationPath, $files, "NewPdf.pdf");
}