且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中将html转换为pdf?

更新时间:2023-01-23 08:48:47

Use wkhtmltopdf via a system call. See How to install wkhtmltopdf on a linux based (shared hosting) web server for installation help.

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.

See the sample from this page here.

php code tested on Ubuntu (you'll need to change the /tmp/ to a temporary directory on Windows):

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

There are also php bindings which removes the need to use a system call yourself, which is a simpler (and safer!) option.

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