【问题标题】:DOMPDF how to add Page NumberDOMPDF如何添加页码
【发布时间】:2019-02-09 00:26:18
【问题描述】:

我已经检查了与此问题相关的所有答案,但没有成功。

我想在页脚中添加页码,我已经尝试过下面的代码,但没有成功。谁能告诉我哪里出错了?

$dompdf = new Dompdf();
$dompdf->set_option("isPhpEnabled", true);
$html_content = "
<html>
<head>
<style>
@font-face {
  font-family: kindergarten;
  font-weight: normal;
  font-style: normal;
  src: url('fonts/kindergarten.ttf') format('truetype');
}
.test{  font-family: kindergarten;  }
</style>

</head>
<body>
<script type='text/php'>
if ( isset($pdf) ) { 
    $pdf->page_script('

            $font = $fontMetrics->get_font('Arial, Helvetica, sans-serif, 'normal');
            $size = 12;
            $pageText = 'Page 1';
            $y = 15;
            $x = 520;
            $pdf->text($x, $y, $pageText, $font, $size);

    ');
}
</script>
<div>My Content goes here</div>
</body>
</html>
"; 
//echo $html_content; die;
$dompdf->loadHtml($html_content);
$dompdf->render();

【问题讨论】:

    标签: php dompdf


    【解决方案1】:

    使用公共方法page_text()

    // Documentation
    
     * @param float  $x
     * @param float  $y
     * @param string $text       the text to write
     * @param string $font       the font file to use
     * @param float  $size       the font size, in points
     * @param array  $color
     * @param float  $word_space word spacing adjustment
     * @param float  $char_space char spacing adjustment
     * @param float  $angle      angle to write the text at, measured CW starting from the x-axis
    

    我的例子(https://prnt.sc/mifmxl):

    $html   = 'Text to test...';
    $dompdf = new Dompdf();
    
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    
    // Parameters
    $x          = 505;
    $y          = 790;
    $text       = "{PAGE_NUM} of {PAGE_COUNT}";     
    $font       = $dompdf->getFontMetrics()->get_font('Helvetica', 'normal');   
    $size       = 10;    
    $color      = array(0,0,0);
    $word_space = 0.0;
    $char_space = 0.0;
    $angle      = 0.0;
    
    $dompdf->getCanvas()->page_text(
      $x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle
    );
    
    // stream
    $dompdf->stream('pdf_out.pdf', array('Attachment' => false));
    

    版本:DomPDF (v0.8.3)

    【讨论】:

    • 感谢您的回答。我有 v0.8.3,但无法访问 FontMetrics 类。
    • 如果这有助于回答您的问题,请选择此作为答案。
    • 谢谢你,你的建议对我很有效。干杯!
    • 在 0.8.3 版本中不推荐使用“get_font”方法。可能应该使用一个“getFont”版本。我在这个版本的 dompdf 中的任何地方都找不到“get_text”方法,并且 VSCode 给出了错误。我使用了一个更简单的解决方案,其中包含 CSS 和页眉、页脚和 main。给出页码(但不计数)。在ourcodeworld.com/articles/read/687/… 找到它
    猜你喜欢
    • 1970-01-01
    • 2017-05-07
    • 2013-09-05
    • 2023-04-08
    • 2012-10-21
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多