为什么使用此代码生成的PDF的质量如此之低?

时间:2011-06-02 19:36:08

标签: php pdf pdf-generation imagick

我有以下代码。它用于将各种图像附件(和pdfs)组合成一个PDF。出于某种原因,当我拍摄一张PDF并将其放入代码时,最终结果看起来与原始PDF相比非常糟糕。另外,我可以在源PDF中选择文本,但在生成的文本中我不能。

非常感谢任何帮助。

// PDF object
$pdf = new Imagick();
$max_resolution = array('x' => 100, 'y' => 100);

foreach($attachment_ids as $attachment_id) {
    $attachment = DAO_Attachment::get($attachment_id);
    $file = Storage_Attachments::get($attachment);
    // Temporarily store our attachment
    $im = new Imagick();
    $im->readImageBlob($file);
    // We need to reset the iterator otherwise only one page will be rotated
    $im->resetIterator();

    // Get the resolution
    $resolution = $im->getImageResolution();
    if($resolution['x'] > $max_resolution['x']) {
        $max_resolution['x'] = $resolution['x'];
    }
    if($resolution['y'] > $max_resolution['y']) {
        $max_resolution['y'] = $resolution['y'];
    }

    $num_pages = $im->getNumberImages();

    $rotation = array_shift($rotations);
    $degrees = $rotation > 0 ? 360 - $rotation : 0;
    $pages = array();

    if($degrees > 0) {
        // Rotate each page
        for($i = 1; $i <= $num_pages; $i++) {
            $im->nextImage();
            $im->rotateImage(new ImagickPixel(), $degrees);
        }
    }

    // We need to reset the iterator again so all of our pages will be added to the pdf
    $im->resetIterator();

    // If the image format isn't a pdf, convert it to a png
    if($im->getImageFormat !== 'pdf') {
        $im->setImageFormat('png');
        // Opacity
        if(method_exists($im, 'setImageOpacity'))
            $im->setImageOpacity(1.0);
    }

    $im->setImageCompression(imagick::COMPRESSION_LOSSLESSJPEG); 
    $im->setImageCompressionQuality(100);
    $im->stripImage();

    // Add the rotated attachment to the PDF
    $pdf->addImage($im);

    // Free
    $im->destroy();
}

// Create a composite
$pdf->setImageFormat('pdf');

// Compress output
$pdf->setImageCompression(imagick::COMPRESSION_LOSSLESSJPEG); 
$pdf->setImageCompressionQuality(100);
$pdf->stripImage();

// Set resolution
$pdf->setImageResolution($max_resolution['x'], $max_resolution['y']);

3 个答案:

答案 0 :(得分:1)

这对您来说可能很明显,但低质量的图像不会产生高质量的PDF格式。我不知道Imagick的pdf生成功能有多好,但是你的代码似乎是在转换图像?您可以通过与TcPDF做同样的事情来比较,但如果图像质量低,我怀疑你会得到更好的结果。

此外,如果您可以访问比通常的网络优化格式更高的DPI分辨率图像,我建议您使用它们来构建PDF。质量会好很多。

答案 1 :(得分:1)

ImageMagick使用GhostScript将PDF转换为各种光栅图像格式。 GhostScript在这方面相当擅长,但是你可以通过将页面缩小到最大100x100来手工制作它。

72 dpi的8.5x11(英寸)页面,为612x792像素。

也许您打算限制DPI而不是解决方案?输出仍然不能很好地扩展(矢量格式与像素格式),但我怀疑这将是一个很大的改进。

答案 2 :(得分:1)

事实证明,答案是使用setResolution()设置DPI。我们在之前使用readImageBlob()来读取包含我们图像的文件,因为它会根据当前分辨率更改图像的DPI(因此之后设置它将无效)

您也可以使用一些数学并在事后使用resampleImage()来完成,但setResolution()似乎对我们有效。