php - 使用 Zend_Pdf 时出现 PDF 文档错误

标签 php zend-framework magento magento-1.7 zend-pdf

在magento1.7中,我在自定义 Controller 中尝试了如下所示的操作。

public function getPDF()
{
$imagePath=C:\Users\.........;
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$page->drawImage($image, 40,764,240, 820);
.
.
.
$pdf->pages[] = $page;
$pdf->save("mydoc.pdf");
}

没有错误。它生成带有图像的 PDF,但 PDF 文档保存在 magento 文件夹中,而不是保存在“我的下载”文件夹中。经过一些研究后,我发现了一些以下的行 block 并将它们添加到 $pdf->pages[] = $page; 之后。

  $pdfString = $pdf->render();
  header("Content-Disposition: attachment; filename=myfile.pdf");
  header("Content-type: application/x-pdf");
  echo $pdfString;

现在它会在“我的下载”文件夹中生成 PDF。当我尝试打开它时。它会抛出错误:Adobe reader 无法打开 myfile.pdf,因为它不是受支持的文件类型或因为文件已损坏............当我们尝试打开时会发生这种情况PDF 文档在本地主机上生成或有其他原因。请告诉我为什么会出现此错误,并为我提供解决方案。

最佳答案

您的问题可能是由于同时调用 save() 和 render() 造成的。

save() 实际上调用了 render(),问题可能是由于尝试渲染 PDF 两次所致。

这也是一种资源浪费,如果您需要保存文件,最好先保存文件,然后直接将该文件提供给用户。

您可以在普通的旧 PHP 中执行此操作(使用 passthru 或 readfile),尽管在 Zendframework 中有一些方法可以执行此操作,您可以研究一下更好的方法:)

// .. create PDF here.. 
$pdf->save("mydoc.pdf");

$file = 'mydoc.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

如果您的代码位于 Magento Controller 内:

    $this->getResponse()
        ->setHttpResponseCode(200)
        ->setHeader('Pragma', 'public', true)
        ->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
        ->setHeader('Content-type', $contentType, true)
        ->setHeader('Content-Length', filesize($file))
        ->setHeader('Content-Disposition', 'attachment; filename="'.$fileName.'"')
        ->setHeader('Last-Modified', date('r'));

    $this->getResponse()->clearBody();
    $this->getResponse()->sendHeaders();

    $ioAdapter = new Varien_Io_File();
    if (!$ioAdapter->fileExists($file)) {
        Mage::throwException(Mage::helper('core')->__('File not found'));
    }
    $ioAdapter->open(array('path' => $ioAdapter->dirname($file)));
    $ioAdapter->streamOpen($file, 'r');
    while ($buffer = $ioAdapter->streamRead()) {
        print $buffer;
    }
    $ioAdapter->streamClose();
    exit(0);

关于php - 使用 Zend_Pdf 时出现 PDF 文档错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131038/

相关文章:

php - Laravel: Eloquent orderBy hasOne 关系列使用 with

php - Tesseract 与 PHP 性能

php - ZF2 : Dependency injection done the proper way

php - 如何从 Magento 的主页提供忘记密码的链接?

mysql - 在 Solr 中搜索

php - CLI php中的printf在行尾打印额外的数字

php - 本地化 .po 文件格式

php - 如何在 PHP 中输​​出 HackerRank 的简单数组求和挑战?

mysql - Zend Framework中自动引用MySQL查询疑惑

php - 在准备好的 Jquery 文档上运行 php 脚本