如何在Dompdf中添加页眉和页脚?

时间:2013-09-02 10:03:33

标签: php dompdf

我使用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插入页眉和页脚,特别是在哪里放置标题代码?

1 个答案:

答案 0 :(得分:4)

来自dompdf FAQ

  

问:如何在每个页面上向页眉或页脚添加图像?   A:你   可以使用添加图像和形状(线条,矩形等)到每个页面   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变量是否已设置。在评估嵌入式PHP时,dompdf设置此变量。

<script type="text/php">

if ( isset($pdf) ) {