我想将两个PDF文件(分别为300毫米宽和150毫米高)合并为SRA3(450毫米宽和320毫米高)尺寸页面。 第一个PDF将从右上角插入,而secoend PDF将从右下角插入。
我尝试过https://github.com/myokyawhtun/PDFMerger,但它只是一个接一个地合并PDF。
<?php
$attached_files = ['file1.pdf', 'file2.pdf'];
$pdf = new \PDFMerger;
foreach ( $attached_files as $attached_file ) {
$pdf->addPDF( $attached_file, 'all' );
}
$file_name = 'orders-pdf-' . uniqid() . '.pdf';
$pdf->merge( 'download', $file_name );
有人可以给我一些示例代码吗?
答案 0 :(得分:0)
基于@arkascha注释,我构建了一个将两个pdf合并为新pdf的函数。我正在共享我的代码,以便任何人都可以找到它。
function combinePdf( $filePath1, $filePath2 ) {
// Each actual PDF size is (850.394 * 425.197) points
// New PDF size need to be SRA3 (1275.8 * 907.2) points
// Imagick default resolution if resolution not set
$default_resolution = 72;
// Multiplier to make resolution around 300
$multiplier = 4.167;
// We found around 300 resolution looks like original image
$resolution = ( $default_resolution * $multiplier ); // 300
// Read first PDF file
$pdf1 = new \Imagick();
$pdf1->setResolution( $resolution, $resolution );
$pdf1->readImage( $filePath1 );
// Read second PDF file
$pdf2 = new \Imagick();
$pdf2->setResolution( $resolution, $resolution );
$pdf2->readImage( $filePath2 );
// Build new SRA3 size PDF
$newPdf = new \Imagick();
$newPdf->setResolution( $resolution, $resolution );
$newPdf->newImage( 1275.8 * $multiplier, 907.2 * $multiplier, "white" );
$newPdf->setImageFormat( 'pdf' );
// Calculate column offset of the composited PDF
$x = ( 1275.8 * $multiplier ) - ( 850.394 * $multiplier );
// Calculate row offset of the second composited PDf
$y = ( 907.2 * $multiplier - ( $pdf2->getImageHeight() * 2 ) ) + $pdf2->getImageHeight();
// Composite first and second PDF into new PDF
$newPdf->compositeImage( $pdf1, \Imagick::COMPOSITE_DEFAULT, $x, 0 );
$newPdf->compositeImage( $pdf2, \Imagick::COMPOSITE_DEFAULT, $x, $y );
// Get image string
$image = $newPdf->getImageBlob();
return $image;
}