Interlated
Interlated

Reputation: 5926

How to load CSS and images with KnpSnappyBundle PDF and Symfony2?

I am getting an Authentication Required error on loading CSS and image resources.

Error example:

Warning: Failed to load http://reporter.dev:8888/css/fc84af4_part_1_bootstrap-editable_2.css (ignore)

I am using the KNP Snappy bundle as follows:

$html = $this->renderView(
  'InterlatedReporter:Allocation:casual_calendar_pdf.html.twig',
  array(
    'casualCalendar' => $casualCalendar,
  )
);

$filename = "export-casual-calendar-" . date("Ymd") . '.pdf';

return new Response(
  $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
  200,
  array(
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'attachment; filename="' . $filename . '"'
  )
);

The twig template has had absolute paths added to it as follows. The URL's seem to to use file://

{{ app.request.getSchemeAndHttpHost() ~ asset('css/sortable-theme-bootstrap.css') }}

I have tried working with security, the dev firewall is in place:

dev:
    pattern:  ^/(_(profiler|wdt)|css|images|js)/
    security: false

This is the first rule.

We are using controller annotations as per SensioFrameworkExtraBundle.

I have also tried passing the session as per Symfony 2 kpn snappy generate pdf with output meets security area

How to load the resources?

Upvotes: 2

Views: 6423

Answers (2)

Guillaume Orsoni
Guillaume Orsoni

Reputation: 1

I had the same issue, and Interlated said, add a base directory before the asset('path/to/your/asset/or/image') fix the problem.

If you can't access the $this->get('kernel') or $request (for example in a listener), you can do it "manually" with the __DIR__ magic constant !

My listener is in ./my-project/src/MyBundle/Listener/MyListener.php and my $basedir = __DIR__.'/../../../web'

So in your twig view <img src="{{ basedir ~ asset('path/to/your/img')}}" alt="">

Upvotes: 0

Interlated
Interlated

Reputation: 5926

I found a fix. The file:// was the key.

Pass, a base directory to the template:

$html = $this->renderView(
  'InterlatedReporter.html.twig',
  array(
    'casualCalendar' => $casualCalendar,
    'base_dir' => $this->get('kernel')->getRootDir() . '/../web' . $request->getBasePath()
  )
);

And provide the full path to the assets:

<link rel="stylesheet" href="{{ base_dir ~ asset('css/sortable-theme-bootstrap.css') }}">

Upvotes: 7

Related Questions