Skip to content

Instantly share code, notes, and snippets.

@oblank
Created July 29, 2015 08:59
Show Gist options
  • Save oblank/3a86003f72d6d3e32480 to your computer and use it in GitHub Desktop.
Save oblank/3a86003f72d6d3e32480 to your computer and use it in GitHub Desktop.
利用 wkhtmltopdf 将html转换成 pdf
$html = '<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head>
<body>'.$html.'</body>
</html>';
//echo $html;
//将本地 HTML 文件转为 PDF
// Run wkhtmltopdf
$descriptorspec = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w'), // stderr
);
$process = proc_open('wkhtmltopdf -q - -', $descriptorspec, $pipes);
// Send the HTML on stdin
fwrite($pipes[0], $html);
fclose($pipes[0]);
// Read the outputs
$pdf = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
// Close the process
fclose($pipes[1]);
$return_value = proc_close($process);
// Output the results
if ($errors) {
print_r ('PDF generation failed: ' . $errors);
} else {
$file_name = "数据分析(".date("Y-m-d H:i:s").")";
header('Content-Type: application/pdf');
header('Cache-Control: public, must-revalidate, max-age=0'); // HTTP/1.1
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s').' GMT');
header('Content-Length: ' . strlen($pdf));
header('Content-Disposition: inline; filename="' . $file_name . '";');
echo $pdf;
}
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment