dompdf - text on a single page / page_script doesn

2019-06-08 15:42发布

问题:

I'm using dompdf 0.7.0 and try to write down text in PHP on my pdf after rendering. I need text on specific pages and found the following from Answer from Brian DomPDF {PAGE_NUM} not on first page

The function page_script sound like the correct answer. I could check if loop is currently on page 3 or whatever.

Does I have to enable any options for this function?

Example:

    $dompdf = new Dompdf( $options );
    $dompdf->set_option('default_font', 'open sans');
    $dompdf->set_option('fontHeightRatio', 1);
    $dompdf->setPaper('A4')


    $dompdf->set_option('enable_html5_parser', true);
    $dompdf->set_option('enable_php', true);

    $dompdf->loadHtml( $html );
    $dompdf->render();

    $canvas = $dompdf->get_canvas();
    $canvas->page_script('
    if ($PAGE_NUM > 1) {
        $current_page = $PAGE_NUM-1;
        $total_pages = $PAGE_COUNT-1;
        $canvas->text(0, 0, "$current_page / $total_pages", "open sans condensed", 10, array(0,0,0));
    }
   ');

It still be shown on my first page.

回答1:

$canvas wouldn't be available from the page script as it is out of scope. The canvas object can be referenced inside your page script as $pdf.

Try the following page_script call instead:

$canvas->page_script('
  if ($PAGE_NUM > 1) {
    $current_page = $PAGE_NUM-1;
    $total_pages = $PAGE_COUNT-1;
    $font = $fontMetrics->getFont("open sans condensed", "normal"); // or bold, italic, or bold_italic
    $pdf->text(0, 0, "$current_page / $total_pages", $font, 10, array(0,0,0));
  }
};

There are a few variables available from within page scripts or embedded script:

  • $PAGE_NUM: current page number
  • $PAGE_COUNT: total number of pages
  • $pdf: the canvas object
  • $fontMetrics: an instance of the FontMetrics class

If you're using page text you have access to the following template variables:

  • {PAGE_NUM}: current page number
  • {PAGE_COUNT}: total number of pages

Note: Support for parsing embedded script or page scripts is disabled by default. Enable it with the following command: $dompdf->set_option("isPhpEnabled", true);. This must be done prior to calling $dompdf->render();.



标签: php dompdf