【问题标题】:How to add Header and Footer in Dompdf?如何在 Dompdf 中添加页眉和页脚?
【发布时间】:2013-09-05 09:40:04
【问题描述】:

我正在使用 Dompdf 生成一个 html2pdf,我的代码是

$html='<div>--content of pdf--</div>';
require_once('resources/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
$dompdf->stream("transaction.pdf");

我的 pdf 已成功生成,现在我想在该 pdf 的页眉中添加图像,那么任何人都可以告诉我如何为 Dompdf 插入页眉和页脚,特别是在哪里放置页眉代码?

【问题讨论】:

标签: php dompdf


【解决方案1】:

来自dompdf FAQ

问:如何在每页的页眉或页脚中添加图片? 答:你 可以使用向每个页面添加图像和形状(线、矩形等) PDF“对象”。 PDF 对象将所有呈现命令捕获为一个排序 然后可以将模板添加到多个页面:

<script type="text/php">

if ( isset($pdf) ) {

  // Open the object: all drawing commands will
  // go to the object instead of the current page
  $footer = $pdf->open_object();

  $w = $pdf->get_width();
  $h = $pdf->get_height();

  // Draw a line along the bottom
  $y = $h - 2 * $text_height - 24;
  $pdf->line(16, $y, $w - 16, $y, $color, 1);

  // Add an initals box
  $font = Font_Metrics::get_font("helvetica", "bold");
  $text = "Initials:";
  $width = Font_Metrics::get_text_width($text, $font, $size);
  $pdf->text($w - 16 - $width - 38, $y, $text, $font, $size, $color);
  $pdf->rectangle($w - 16 - 36, $y - 2, 36, $text_height + 4, array(0.5,0.5,0.5), 0.5);

  // Add a logo
  $img_w = 2 * 72; // 2 inches, in points
  $img_h = 1 * 72; // 1 inch, in points -- change these as required
  $pdf->image("print_logo.png", "png", ($w - $img_w) / 2.0, $y - $img_h, $img_w, $img_h);

  // Close the object (stop capture)
  $pdf->close_object();

  // Add the object to every page. You can
  // also specify "odd" or "even"
  $pdf->add_object($footer, "all");
}

</script>

编辑:

以下是分步说明:

在您的 html 文件的某个位置,靠近顶部,打开一个带有“text/php”类型的脚本标签:

<script type="text/php">

检查是否设置了 $pdf 变量。 dompdf 在评估嵌入式 PHP 时设置此变量。

<script type="text/php">

if ( isset($pdf) ) {

【讨论】:

  • 把这个脚本放在哪里?在生成 pdf 之前或生成 pdf 之后。我们可以把这个脚本放在 php 标签中吗?
  • 请注意,如果使用内联脚本,它当前需要驻留在 HTML 的 body 中。由于文档的解析方式,您至少需要将 HTML 格式设置为 &lt;body&gt;&lt;script type="text/php"&gt;...&lt;/script&gt;&lt;div&gt;--content of pdf--&lt;/div&gt;&lt;/body&gt;。如果可以的话,只需使用 HTML+CSS 创建页眉/页脚。
猜你喜欢
  • 2023-04-08
  • 2019-10-04
  • 2012-03-07
  • 2011-11-27
  • 1970-01-01
  • 2020-02-15
  • 2020-06-27
相关资源
最近更新 更多