使用 PHP Imagick 库将图像转换为 PDF 时如何指定 PDF 页面大小和方向?

问题描述 投票:0回答:1

我正在 PHP 中将图像转换为 PDF。如何将图像显示在 8.5 x 11 英寸的纵向页面上?我似乎找不到一个设置来做到这一点。我得到的是一个与图像大小相同的 PDF 页面。

$imagick = new Imagick();
$source_handle = fopen( $source_image, 'a+' );
$imagick->readImageFile( $source_handle );
fclose( $source_handle );
$imagick->setFormat('PDF');
$output_handle = fopen( $destination_pdf, 'w' );
$imagick->writeImageFile( $output_handle );
fclose( $output_handle );
php pdf imagick
1个回答
0
投票

我最终解决了这个问题如下:

  1. 在 imagick 对象中打开图像文件。
  2. 创建另一个 imagick 对象,它是具有所需尺寸和分辨率的空白 PDF。
  3. 使用compositeImage()方法将图像放置在PDF页面上。

生成的页面在 PDF 阅读器中被识别为美国信函大小的页面。 这是我的代码:

$max_width = 1700;
$max_height = 2200;

$scan = new Imagick();
$scan->setResolution( 200, 200 );
$source_handle = fopen( $source_image, 'a+' );
$scan->readImageFile( $source_handle );
$scan->setImageUnits( imagick::RESOLUTION_PIXELSPERINCH );
fclose( $source_handle );

// Resize the image if it doesn't fit on the page
$scan->setImageResolution( 200 );
$scan->resampleImage();
$image_data = $scan->identifyImage();
$original_width = $image_data['geometry']['width'];
$original_height = $image_data['geometry']['height'];
    
if ( $original_width > $max_width or $original_height > $max_height )
    { $scan->thumbnailImage( $max_width, $max_height, true); }
$final_width = $scan->getImageWidth();
$final_height = $scan->getImageHeight();

// Set up the PDF page
$pdf = new Imagick();
$pdf->newImage( $max_width, $max_height, new ImagickPixel('white'));
$pdf->setImageFormat('PDF');
$pdf->setImageUnits( imagick::RESOLUTION_PIXELSPERINCH );
$pdf->setResolution( 200,200 );

// Place the scanned image on the PDF page
if ( $final_width > 1500 )
    { $x = 1; }
else
    { $x = 100; }

if ( $final_height > 2100 )
    { $y = 1; }
else
    { $y = 100; }
    
$pdf->compositeImage( $scan, Imagick::COMPOSITE_DEFAULT, $x, $y );
unset( $scan );

// Write out the PDF
if ( file_exists( $destination_pdf ) )
    { unlink( $destination_pdf ); }
$output_handle = fopen( $destination_pdf, 'w' );
$pdf->writeImageFile( $output_handle );
© www.soinside.com 2019 - 2024. All rights reserved.