DEV Community

How I can convert a blade content into PDF?

Dimitrios Desyllas on November 10, 2020

How I can convert a blade content into PDF? Nov 1...
Collapse
 
llagerlof profile image
Lawrence Lagerlof

I used many solutions, including DOMPDF, but on average the output generated by WKHTMKTOPDF is far better than DOMPDF.

WKHTMKTOPDF follow CSS rules more precisely.

Well, wkhtmltopdf is a command line program that accepts an html file as parameter, so you just have to install it and you are ready to go. It has package for Linux and Windows.

To the code

Generate the desired html from your view, like this:

$html = view('my_view', $arr);
Enter fullscreen mode Exit fullscreen mode

Write the HTML to a temporary file:

$temp_file = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($temp_file, $html);
Enter fullscreen mode Exit fullscreen mode

Run exec() on wkhtmltopdf:

$pdf_file = $temp_file . '.pdf';
exec('wkhtmltopdf ' . $temp_file . ' ' . $pdf_file);
Enter fullscreen mode Exit fullscreen mode

Download your $pdf_file.

Be happy.

Collapse
 
nathandaly profile image
Nathan Daly

Used DOMPDF before with some issues with images. I recommend using Browsershot instead as it can handle any images and CSS.

The only drawback is it cannot merge PDF's, so you will have to merge PDF pages in your own PHP code.

github.com/spatie/browsershot

Collapse
 
llagerlof profile image
Lawrence Lagerlof

Please, add the tag #help in this post.