内联php脚本变量在DOMPDF中不起作用

时间:2017-10-10 12:23:09

标签: php dompdf html-to-pdf

当我生成pdf时,内联php脚本没有执行,只有html部分在pdf上打印。我已设置$ isPhpEnabled = True。

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$abc="This is the php text";
$html = <<<'ENDHTML'
<html>
<head>
<style>
h1{color:#555555;width:100%;border-bottom:2px solid powderblue;}
</style>
</head>
 <body>
  <h1 >Name : <script type="text/php"> echo $abc; </script></h1>
 </body>
</html>
ENDHTML;
$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream("dompdf_out.pdf", array("Attachment" => false));
exit(0);
?>

2 个答案:

答案 0 :(得分:2)

尝试

<?php
// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$abc="This is the php text";
$html = "
<html>
<head>
<style>
h1{color:#555555;width:100%;border-bottom:2px solid powderblue;}
</style>
</head>
 <body>
  <h1 >Name : $abc</h1>
 </body>
</html>
";
$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream("dompdf_out.pdf", array("Attachment" => false));
exit(0);
?>

答案 1 :(得分:0)

诀窍是简单地将html呈现为php中的字符串,并将其与希望在PDF中显示的值连接在一起。 您必须谨慎使用引号,因为标记中会包含双引号。因此,如果您了解我的意思,则可以使用单引号作为包装。

类似这样:

$html = '<div class = "some class" >' . $variable . '</div>';

然后可以将此字符串加载到$ dompdf实例中。 $ variable可能会从任何地方(例如数据库)获取其价值,或者您可能要遍历循环以构建布局元素。