要将HTML转换为PDF,可以使用PHP的第三方库,例如dompdf
。以下是使用dompdf
将HTML转换为PDF的步骤:
dompdf
库。你可以从官方网站下载,或者使用Composer进行安装:composer require dompdf/dompdf
dompdf
库,并创建一个新的Dompdf
实例:require_once 'vendor/autoload.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$html = '<!DOCTYPE html>
<html>
<head>
<title>Example HTML to PDF</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is an example of converting HTML to PDF using dompdf.</p>
</body>
</html>';
$dompdf->loadHtml($html);
$dompdf->set_option('isRemoteEnabled', true);
$dompdf->set_option('isHTML5ParserEnabled', true);
$dompdf->set_option('isFontSubstitutingEnabled', true);
$dompdf->set_option('defaultMediaType', 'html');
$dompdf->set_option('paperSize', 'a4');
$dompdf->set_option('paperOrientation', 'portrait');
$dompdf->render();
$pdf = $dompdf->output();
// 保存到文件
file_put_contents('example.pdf', $pdf);
// 直接发送到浏览器
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="example.pdf"');
echo $pdf;
将以上代码整合到一个完整的PHP脚本中,即可实现将HTML转换为PDF的功能。