laravel-dompdf print with text watermark in every page


 

I stuck with a problem that is print watermark text to every page. after searching various areas of internet i found a working solution to my problem. i'm now shearing it. so it will useful to someone who have same problem

first you have to install laravel-dompdf wrapper.

then need to add 'PDF' word to app config aliases list(rootfolder/config/app.php)

'PDF' => Barryvdh\DomPDF\Facade::class,

import pdf class to controller(or any kind of class object)

use PDF;

create pdf wrapper object by loading blade file to laravel-dompdf

$pdf = PDF::loadView('print.view', compact('yourviewdata'));

set paper size (i set L means 'letter size')

$pdf->setPaper('L');

then need to render it(we can't call dompdf render function directly. we can use output function for that comes with laravel-dompdf

$pdf->output();

now this need to get core dompdf object from laravel-dompdf wrapper to get canvas(canvas need to add watermark). here how it do

$canvas = $pdf->getDomPDF()->getCanvas();

getting canvas height and width. this is optional.

$height = $canvas->get_height();
$width = $canvas->get_width();

so i need to place every page this watermark opacity(transparency) for that i used like this .'Multiply' means add it to every page.

$canvas->set_opacity(.2,"Multiply");

if you want set opacity to one page just use as

$canvas->set_opacity(.2);

now need to place text to every page.

$canvas->page_text($width/5, $height/2, 'This Is Watermark text', null,
 70, array(0,0,0),2,2,-30);


function parameter names:

page_text(x axis value, y axis value, 'your text, font(or null), font size,rgb color array, word space, char space, angle(- or +));


to prview it on browser we can use as usual

return $pdf->stream();

or download on visit to link

return $pdf->download('yourpdf.pdf');


here final code example 

namespace App\Http\Controllers;
use PDF;
use App\Http\Controllers\Controller;
use App\Datamodel; 
class PrintController extends Controller
{

public function Print()
{
$yourviewdata = Datamodel::all();
$pdf = PDF::loadView('print.view', compact('yourviewdata'));
$pdf->setPaper('L');
$pdf->output();
$canvas = $pdf->getDomPDF()->getCanvas();
$height = $canvas->get_height();
$width = $canvas->get_width();
$canvas->set_opacity(.2,"Multiply");
$canvas->page_text($width/5, $height/2, 'This Is Watermark text', null,
         70, array(0,0,0),2,2,-30);
return $pdf->stream();
}

}



thats all..

Comments

Popular posts from this blog

Handling undefined variables in laravel

How to use Spatie packages to enhance your Laravel development experience

Some Briefs of Data Mining