【问题标题】:Zend Framework PDF problemsZend Framework PDF 问题
【发布时间】:2010-11-22 16:37:28
【问题描述】:

又是我,伙计们,我有一个小问题:

        // 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(); 

当我下载文件并尝试打开它时,我收到一个错误,听起来像这样:

格式错误:不是 PDF 或已损坏

我的问题是:我做错了什么?

【问题讨论】:

    标签: php zend-framework pdf


    【解决方案1】:

    如果您尝试使用文本编辑器(或十六进制编辑器)打开文件,您会得到什么?

    您的 PDF 文件必须只包含 PDF 数据,并且不能在开头或结尾包含任何 HTML 或空格。

    可能导致麻烦的一件事是 Zend Framework 自动呈现视图。
    在你的行动开始时使用这样的东西可能会有所帮助:

    $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());
    }
    

    据我所知,几个月前它运行良好;与您的代码的唯一区别是:

    • 禁用布局/渲染
    • 使用徽标;但这不应该有太大的区别


    希望这可以帮助 ;玩得开心!

    【讨论】:

    • 你也可以说我,我怎样才能创建一个空格?我的意思是一个换行符,像
      \n...因为我有一个长文本
    • 太好了,你自己解决了这个问题:实际上,我使用 Zend_Pdf 的次数并不多……除了我之前展示的小例子之外,没有太多:-D
    猜你喜欢
    • 2010-11-22
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多