7

Rails 2, PDFkit 0.5.0

Im generating a PDF from a View in Rails 2 with PDFkit and everything works fine. The only thing which doesn't work is displaying pictures in the pdf.

When I look at the View in the Browser, the picture is there but its missing in the PDF. There is only a placeholder existing in the PDF.

The image_tag is looking like this:

<%= image_tag('plus.gif') %>

I also tried to realize it with a css-file but it doesn't work either.

Any ideas?

MarkoHiel
  • 15,481
  • 2
  • 21
  • 29

2 Answers2

14

Because of the way that wkhtmltopdf works you need to specify the full path to any assets (JS, CSS, images etc), including the domain name.

This won't work:

<img src="/images/foo.png" />

This will:

<img src="http://example.com/images/foo.png" />

One workaround is to set an explicit asset host, even if it's the same server as your app is running on (see the AssetTagHelper documentation for details). Another would be to specify the hostname in the image_tag.

maerics
  • 151,642
  • 46
  • 269
  • 291
nfm
  • 19,689
  • 15
  • 60
  • 90
  • 3
    Thx that works! <%= image_tag("#{RAILS_ROOT}/public/images/foo.png")%> – MarkoHiel May 24 '11 at 14:24
  • That won't work if you want to render the view in your browser and also generate a PDF from it - depends on your requirements. – nfm May 25 '11 at 00:36
  • 5
    Also note if you are using full URL in your img tags you will need to be running a multi-{thread, process} server, such as unicorn, in development as it will need to process two requests at once. – Kris Jul 03 '13 at 08:57
  • RAILS_ROOT has been deprecated since Rails 3.0. What should I do instead? – fatuhoku May 03 '16 at 16:40
  • @fatuhoku Rails.root serves the same purpose as far as I know. – Dennis L Nov 05 '16 at 19:41
  • <%= image_tag(image_url("kunzig-logo.png", host: "http://localhost:3000/"), style: "width: 100%;") %> This made it so I can preview in dev. Just be sure to change the host option after lol – bkunzi01 Mar 17 '17 at 19:55
0

Instead of putting the full path each time, you can add a base tag to the head section.

<base href="http://mydomain.com" target="_blank" />
Pablo
  • 300
  • 2
  • 5