【问题标题】:inline php script variables not working in DOMPDF内联 php 脚本变量在 DOMPDF 中不起作用
【发布时间】:2018-03-21 20:35:27
【问题描述】:

当我生成 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);
?>

【问题讨论】:

  • 你的意思是$abc 没有打印吗?
  • @ParitoshMahale 是的。
  • @ParitoshMahale 如何在 html 代码中执行脚本,因为我想生成动态内容?
  • 类似$a = array('one','two','three','four','five'); $abc="This is the php text"; $html = " &lt;html&gt; &lt;head&gt; &lt;style&gt; h1{color:#555555;width:100%;border-bottom:2px solid powderblue;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; "; foreach($a as $value){ $html .= '&lt;h1&gt;'.$value.'&lt;/h1&gt;'; } $html .='&lt;/body&gt;&lt;/html&gt;'; echo $html;
  • 嵌入式(内联)脚本不会创建文档内容。它的主要目的是提供一种在 PDF 渲染过程中访问 PDF 后端(CPDF、PDFLib)的方法。但我们建议您避免使用嵌入式脚本,因为它会打开一个潜在的安全漏洞,并且您可以使用其他方法进行几乎相同的操作。根据您的描述,您应该只生成 HTML,然后将最终文档提供给 Dompdf。

标签: php dompdf html-to-pdf


【解决方案1】:

试试

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

【讨论】:

  • 如果我想执行一些脚本(如循环)以在 html 代码中的表中输入许多行,因为脚本标签不能直接工作,我应该使用什么? @Paritosh Mahale
  • 现在我只能在 html 字符串中使用变量,但不能使用 php 脚本
【解决方案2】:

诀窍只是将您的 html 呈现为 php 中的字符串,并与您希望在 PDF 中显示的值连接。 您必须小心使用引号,因为您的标记中会有双引号。因此,如果您知道我的意思,使用单引号作为包装器会有所帮助。

比如:

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

然后您可以将此字符串加载到您的 $dompdf 实例中。 $variable 可以从任何地方(例如数据库)提取它的值,或者您可以通过循环迭代来构建布局的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2012-01-31
    • 2011-06-27
    • 1970-01-01
    • 2011-01-10
    • 2012-11-15
    相关资源
    最近更新 更多