在php中将html转换为pdf?

Converting html to pdf in php?

我知道有很多关于这个问题的帖子。但是有人可以帮我设置这个 http://www.rustyparts.com/pdf.php 脚本在我的本地主机上工作。我花了整整一周时间这个问题。我已经下载了imagemagic,ghostscript,activeperl,...,一切,但仍然无法制作简单的示例来工作。


通过系统调用使用 wkhtmltopdf。有关安装帮助,请参阅如何在基于 linux(共享主机)的 Web 服务器上安装 wkhtmltopdf。

wkhtmltopdf is a command line program
which permits to create a pdf from an
url, a local html file or stdin. It
produces a pdf like rendred with the
WebKit engine.

在此处查看此页面中的示例。

在 Ubuntu 上测试的 php 代码(您需要将 /tmp/ 更改为 Windows 上的临时目录):

1
2
3
4
5
6
7
8
9
10
11
$url = 'http://www.google.com';
$pdffile = tempnam('/tmp/', 'wkhtmltopdf_');
$handle = popen("wkhtmltopdf $url $pdffile 2>&1","r");
while (!feof($handle))
  fread($handle, 4096);
pclose($handle);
header('Content-type: application/pdf');
$file = fopen($pdffile,"r");
while(!feof($file))
  print fread($file, 4096);
unlink($pdffile);

还有 php 绑定,无需自己使用系统调用,这是一个更简单(更安全!)的选项。

1
2
3
4
5
6
7
8
try {
    $wkhtmltopdf = new Core_Wkhtmltopdf(array('path' => APPLICATION_PATH . '/../public/uploads/'));
    $wkhtmltopdf->setTitle("Title");
    $wkhtmltopdf->setHtml("Content");
    $wkhtmltopdf->output(Wkhtmltopdf::MODE_DOWNLOAD,"file.pdf");
} catch (Exception $e) {
    echo $e->getMessage();
}


简单但功能强大:http://html2pdf.fr/en/default

1
2
3
4
5
6
7
$html = file_get_contents("valid.html");
require_once("html2pdf.class.php");
$html2pdf = new HTML2PDF("P","A4","en", array(10, 10, 10, 10));
$html2pdf->setEncoding("ISO-8859-1");
$html2pdf->WriteHTML($html);
$html2pdf->Output("pdf/PDF.pdf","F"); //output to file
$html2pdf->Output(); //output to browser


DocRaptor.com 是一个不错的选择 - 它使用 Prince XML,因此质量优于其他工具,而且它是一个网络应用程序,因此无需下载。它也适用于任何语言。


此外,还有另一个生成 PDF 文件的库:TCPDF。很好,很简单。你可以在周围找到很多例子。