DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on • Edited on

How I can convert a blade content into PDF?

1

In my laravel project I have the following myview.blade.php content:

<!DOCTYPE html&gt
<html lang="en">
<head>
     <meta charset="UTF-8">
    <title>{{ __('menu.title') }}</title>
</head>
<body>
 {{__('content') }}
</body>

But instead of rendering it into a http response, I want to be able to generate a pdf file out of it. Do you know…

Top comments (3)

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.