再次是我,我有一个小问题:
// Create new PDF
$pdf = new Zend_Pdf();
// Add new page to the document
$page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
$pdf->pages[] = $page;
// Set font
$page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA), 20);
// Draw text
$page->drawText('Hello world!', 100, 510);
$this->getResponse()
->setHeader('Content-Disposition', 'attachment; filename=result.pdf')
->setHeader('Content-type', 'application/x-pdf');
echo $pdf->render();
当我下载文件并尝试打开它时,出现错误,听起来像这样:
format error: not a PDF or corrupted
我的问题是:我做错了什么?
解决方法:
如果尝试使用文本编辑器(或十六进制编辑器)打开文件,将会得到什么?
您的PDF文件只能包含PDF数据,开头或结尾不得包含任何HTML或空格.
可能引起麻烦的一件事是Zend Framework自动呈现View.
在操作开始时使用类似的方法可能会有所帮助:
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
我看过我写的某个动作的样本,这是我看到的与您所做的唯一的区别,实际上…
如果仍然无法使用,如果您尝试将PDF保存到文件而不是发送给用户怎么办?例如:
$pdf->save(CACHE_DIR . '/test-pdf.pdf');
我知道这不是你想做的;但是它可以让您检查PDF是否生成正确,以识别问题是否出在PDF生成或其输出上.
这是我正在谈论的完整示例:
public function pdfAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$pdf = new Zend_Pdf();
$pdf->properties['Title'] = "TITLE";
$pdf->properties['Author'] = "AUTHOR";
$page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
$width = $page->getWidth(); // A4 : 595
$height = $page->getHeight(); // A4 : 842
$imagePath = WEB_DIR . '/images/logo.png';
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$x = 15;
$y = $height - 15 - 106/2;
$page->drawImage($image, $x, $y, $x+155/2, $y+106/2);
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 36);
$page->drawText('Hello world!', 72, 720, 'UTF-8');
$pdf->pages[] = $page;
$this->getResponse()->setHeader('Content-type', 'application/x-pdf', true);
$this->getResponse()->setHeader('Content-disposition', 'inline; filename=my-file.pdf', true);
$this->getResponse()->setBody($pdf->render());
}
据我所知,这在几个月前还不错;与您的代码的唯一区别是:
>禁用布局/渲染
>使用徽标;但这并没有太大的区别
希望这可以帮助 ;玩得开心!
标签:pdf,zend-framework,php
来源: https://codeday.me/bug/20191024/1920370.html