Dompdf Create Watermark and Page Numbers
02-11-2019$options = new Options(); $options->set('isPhpEnabled', 'true'); $dompdf = new Dompdf($options); $dompdf->setOptions($options); $dompdf->loadHtml('<html>....'); $dompdf->setPaper('A4', ''); $dompdf->render(); // Instantiate canvas instance $canvas = $dompdf->getCanvas(); $w = $canvas->get_width(); $h = $canvas->get_height(); $pageNumberWidth = $w / 2; $pageNumberHeight = $h - 50; $GLOBALS["logo1"]=public_path('images/logo/icon.png'); $GLOBALS["logo2"]=public_path('images/logo/kultur_logo.png'); $canvas->page_script(' if ($PAGE_NUM > 1) { $current_page = $PAGE_NUM-1; $total_pages = $PAGE_COUNT-1; $font = $fontMetrics->getFont("times", "normal"); $pdf->set_opacity(1,"Multiply"); $pdf->text(297.64, 791.89, "$current_page / $total_pages", $font, 10, array(0,0,0)); $pdf->set_opacity(0.2,"Multiply"); $pdf->image($GLOBALS["logo1"], 475.28, 771.89, 50, 50); $pdf->image($GLOBALS["logo2"], 75.28, 771.89, 50, 50); } '); $canvas->set_opacity(.1,'Multiply');//Multiply means apply to all pages. // Specify watermark text $text = "http://www.codesenior.com"; // Instantiate font metrics class $fontMetrics = new FontMetrics($canvas, $options); $font = $fontMetrics->getFont('times'); $txtHeight = $fontMetrics->getFontHeight($font, 150); $textWidth = $fontMetrics->getTextWidth($text, $font, 40); $x = (($w-$textWidth)/2); $y = (($h-$txtHeight)/2); //page_text method applies text to all pages. $canvas->page_text($x, $y, $text, $font, 40,$color = array(255,0,0), $word_space = 0.0, $char_space = 0.0, $angle = 20.0); return $dompdf->stream($project->code . '.pdf', array("Attachment" => 0));
At Line 2: This option must be set because we will use it in the page_script() method at line 17.
At Line 7: To add watermark and page number, we should render HTML content before.
At Line 15, 16: $GLOBALS keyword is used for passing variables to page_script() method.
At Line 22:To prevent the page number opacity from changing , override opacity value defined at line 25.
At Line 25: This opacity value is used for images which are defined at line 26 and 27.
Some Notes:
- page_text() method applies to all pages, but notice that page is starting from zero.
- If you want to ignore first page, you should use æ,$canvas->page_script() method.
- As seen above example, $PAGE_NUM
variable is accessible from page_script() method.
Multiply
in this example, which means apply to all pages. This second parameter is optional. If not specified, default value is Normal