Symfony4 : Problem with KnpSnappy/WkHtmlToPdf

I am trying to set up a pdf file generation system. To do this, I came to use WkHtmlToPdf as well as the KnpSnappy Bundle.
Here’s what i did :

1 – I have first downloaded a precompiled binary (MacOs)

2 – Then installed the bundle : composer require knplabs/knp-snappy ( )

3 – And finally add the bundle in bundles.php with KnpBundleSnappyBundleKnpSnappyBundle::class => ['all' => true],

This is what I wrote in my function, inside my controller:

 * @Route("/pdf/{id}", name="room_pdf", methods={"GET"}, requirements={"id"="d+"})
 * @IsGranted("ROLE_ADMIN")
public function pdf(Room $room, KnpSnappyPdf $knpSnappy)

  $filename = "mypdf";
  $html = $this->renderView('room/show.html.twig' , array(
      'room' => $room,

  return new Response(
     'Content-Type' => 'application/pdf',
     'Content-Disposition' => 'inline; filename="'.$filename.'.pdf"'

I have made several tests, when I try to generate a pdf with an URL or a piece of HTML code I do not encounter any problem, but when I try to generate a pdf based on a twig view using renderView I end up with a pdf of 1777 pages including 1775 blank

Does anyone have an idea of ​​what can be done?

Edit :
I fixed the 1777 pages by loading correctly my css . I add this code at the beginning of my template :

{% block stylesheets %}
    {% for path in encore_entry_css_files('app') %}
        <link rel="stylesheet" href="{{ absolute_url(path) }}">
    {% endfor %}
{% endblock %}

So I end up with a page, almost formatted. My app.js file doesn’t seem loaded so I don’t have all valid bootstrap resources in my pdf

This is what my terminal tells me :

Feb  5 21:52:37 |INFO | SNAPPY File "/var/folders/gv/0qb9br_15gggjmhg5zs_qtth0000gn/T/knp_snappy5e3b390a547d50.44491512.pdf" 
has been successfully generated. stderr="Loading pages (1/6)n[>                                                           ] 
0%r[======>                                                     ] 
10%r[=======>                                                    ] 
Failed to load file:///build/runtime.js (ignore)         
nWarning: Failed to load file:///build/vendors~app.js (ignore)
nWarning: Failed to load file:///build/app.js (ignore)

I added that at the end of my template :

{% block scripts %}
    {% for path in encore_entry_css_files('app') %}
        <script src="{{ absolute_url(path) }}"></script>
    {% endfor %}
{% endblock %} 

And now my console terminal look like that

Feb  5 22:21:42 |INFO | SNAPPY File
has been successfully generated. stderr="Loading pages (1/6)n

But it seems that my bootstrap is not loaded yet..
(It is declared in my app.js with ” require(‘bootstrap’); “)

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *