2

In magento1.7, I have tried something like below in my custom 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");
}

There's no error in it. It generates PDF with image but the PDF document is saved in magento folder instead in My downloads folder. After doing some research, I found some following chunk of lines and added them after $pdf->pages[] = $page;.

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

Now it generates PDF in My Downloads folder. When I try to open it. It throws error saying : Adobe reader couldn't open myfile.pdf because it's not either a supported file type or because the file has been damaged............ Do this happens,when we try to open PDF document generated on localhost or there's some other reason. Please let me know, why this error occurs and also provide me a solution to resolve it.

4

1 回答 1

2

您的问题可能是由于同时调用 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 控制器中:

    $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);
于 2012-11-20T15:34:26.627 回答