【发布时间】:2013-06-25 09:57:03
【问题描述】:
我正在开发一个 Symfony 1.4 项目。我需要为(尚未)生成的凭证制作 PDF 下载链接,我不得不说,我有点困惑。我已经有了凭证的 HTML/CSS,我在右侧视图中创建了下载按钮,但我不知道从那里去哪里。
【问题讨论】:
标签: php pdf-generation symfony-1.4
我正在开发一个 Symfony 1.4 项目。我需要为(尚未)生成的凭证制作 PDF 下载链接,我不得不说,我有点困惑。我已经有了凭证的 HTML/CSS,我在右侧视图中创建了下载按钮,但我不知道从那里去哪里。
【问题讨论】:
标签: php pdf-generation symfony-1.4
Use Mpdf to create the pdf file
http://www.mpdf1.com/
【讨论】:
settings.yml 文件中启用sfTCPDF 模块?
使用 wkhtmltopdf 已经有一段时间了,因为 1) 它有一些严重的错误,并且 2) 正在进行的开发已经放缓。我搬到了PhantomJS,事实证明它在功能和有效性方面要好得多。
一旦你的机器上有 wkhtmltopdf 或 PhantomJS 之类的东西,你需要生成 HTML 页面并将其传递给它。假设你使用 PhantomJS,我会给你一个例子。
初始设置模板所需的每个请求参数。
$this->getRequest->setParamater([some parameter],[some value]);
然后调用函数getPresentation() 从模板生成HTML。这将返回特定模块和操作的结果 HTML。
$html = sfContext::getInstance()->getController()->getPresentation([module],[action]);
您需要将 HTML 文件中的相对 CSS 路径替换为绝对 CSS 路径。例如通过运行preg_replace。
$html_replaced = preg_replace('/"\/css/','"'.sfConfig('sf_web_dir').'/css',$html);
现在将 HTML 页面写入文件并转换为 PDF。
$fp = fopen('export.html','w+');
fwrite($fp,$html_replaced);
fclose($fp)
exec('/path/to/phantomjs/bin/phantomjs /path/to/phantomjs/examples/rasterize.js /path/to/export.html /path/to/export.pdf "A3");
现在将 PDF 发送给用户:
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->setHttpHeader('Content-Description','File Transfer');
$this->getResponse()->setHttpHeader('Cache-Control','public, must-revalidate, max-age=0');
$this->getResponse()->setHttpHeader('Pragma: public',true);
$this->getResponse()->setHttpHeader('Content-Transfer-Encoding','binary');
$this->getResponse()->setHttpHeader('Content-length',filesize('/path/to/export.pdf'));
$this->getResponse()->setContentType('application/pdf');
$this->getResponse()->setHttpHeader('Content-Disposition','attachment; filename=export.pdf');
$this->getResponse()->setContent(readfile('/path/to/export.pdf'));
$this->getResponse()->sendContent();
您确实需要设置标题,否则浏览器会做一些奇怪的事情。生成的 HTML 文件和导出的文件名要唯一,避免两个人同时生成 PDF 凭证的情况发生冲突。您可以使用 sha1(time()) 之类的东西将随机散列添加到标准名称,例如'export_'.sha1(time());
【讨论】:
如果可能,请使用wkhtmltopdf。它是迄今为止 php 编码器可以使用的最好的 html2pdf 转换器。
然后做这样的事情(未经测试,但应该非常接近):
public function executeGeneratePdf(sfWebRequest $request)
{
$this->getContext()->getResponse()->clearHttpHeaders();
$html = '*your html content*';
$pdf = new WKPDF();
$pdf->set_html($html);
$pdf->render();
$pdf->output(WKPDF::$PDF_EMBEDDED, 'whatever_name.pdf');
throw new sfStopException();
}
【讨论】: