DEV Community

Discussion on: How I can convert a blade content into PDF?

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.