将动态 PHP 输出转换为 PDF

Converting Dynamic PHP output to PDF

我想将我的动态 PHP 输出转换为 PDF,我已经寻找答案但找不到有用的答案。我用过 mPDF,但对我来说用处不大。

使用dompdf,可以从here下载。

将你的输出存储在一些变量中并使用下面的代码

用法

require_once 'dompdf/dompdf_config.inc.php';
$html = "<html><body>". $dynamic_output_variable ."
</body></html>";
$pdf = new DOMPDF();
$pdf->load_html($html);
$pdf->render();
$output = $pdf->output();
file_put_contents('output folder/file name.pdf', $output);
$pdf->stream('file name.pdf', array('Attachment' => 0));

您可以使用 DomPdf 库。您可以使用 URL 下载该库的最新版本:https://code.google.com/p/dompdf/downloads/detail?name=dompdf_0-6-0_beta3.tar.gz&can=2&q=

最新版本支持多种字体。

使用以下代码包含库:

require_once("/dompdf/dompdf_config.inc.php");

在浏览器中查看 pdf 输出:

$html = "Your dynamic php output";
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$preview = $dompdf->stream("dompdf.pdf", array('Attachment' => 0));
echo $preview;die;

使用以下代码将 PDF 作为字符串获取:

$pdf = $dompdf->output();

您可以使用以下代码使其可下载:

$filepath//full path of your temporary/public location;
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
file_put_contents($filepath, $pdf); // save the pdf file on server
header("Content-type: application/pdf");
header("Content-Disposition: 'attachment'; filename='dompdf.pdf'");
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
readfile($filepath);
exit();