mileszs/wicked_pdf — Issue #71: pdf_from_string header/footer with url fails randomly
Author: eufrat
Created: 2011-12-28 12:37:38+00:00
State: open

wicked pdf 0.7.2, Ubuntu 11.10, Rails 2.3.14, Ruby 1.8.7 or 1.9.2.

PDF generation fails randomly with following error message

"***************/home/e/projects/dummy/vendor/wkhtmltopdf/wkhtmltopdf-amd64 --header-font-size 8 --header-spacing 10 --header-html '/tmp/wicked_pdf_6185_0.html' --footer-font-size 8 --footer-spacing 2 --footer-html '/tmp/wicked_pdf_6185_1.html' --margin-top 45 --margin-bottom 30 --margin-left 20 --margin-right 20 --page-size 'A4' --print-media-type --disable-smart-shrinking -q - - ***************"
RuntimeError: Failed to execute:
/home/e/projects/askalon/vendor/wkhtmltopdf/wkhtmltopdf-amd64 --header-font-size 8 --header-spacing 10 --header-html '/tmp/wicked_pdf_6185_0.html' --footer-font-size 8 --footer-spacing 2 --footer-html '/tmp/wicked_pdf_6185_1.html' --margin-top 45 --margin-bottom 30 --margin-left 20 --margin-right 20 --page-size 'A4' --print-media-type --disable-smart-shrinking -q - -
Error: PDF could not be generated!

This message is from wicked_pdf rescue clause because wkhtmltopdf-amd64 binary fails due to missing /tmp/wicked_pdf_6185_0.html and/or /tmp/wicked_pdf_6185_1.html file. The file is missing, because somehow it gets randomly deleted. I am not sure which component is responsible - ubuntu, ruby, rails or wicked_pdf.

I created project with 'rails dummy' and then used script/console

1) require 'pry'
2) h11 = WickedPdfTempfile.open('wicked_pdf.html') do |f| f << '<p style="text-align: right">header</p>' end
3) f11 = WickedPdfTempfile.open('wicked_pdf.html') do |f| f << '<p style="text-align: center">footer</p>' end
4) ppp = WickedPdf.new('/home/v/projects/dummy/vendor/wkhtmltopdf/wkhtmltopdf-amd64').pdf_from_string('<p>Hi there</p>',
:header => { :html => {:url => h11.path}, :font_size => 8, :spacing => 10 },
:footer => { :html => {:url => f11.path}, :font_size => 8, :spacing => 2},
:disable_smart_shrinking => true,
:print_media_type => true,
:margin => {:top => 45, :bottom => 30, :left => 20, :right => 20 },
:page_size => 'A4' )
4a) repeat previous step 3 - 5 times to get the error
or save the file like in step 5)
5) File.open('/tmp/foo.pdf', 'wb') do |f| f << ppp end

At the same time watch /tmp folder, and when one of the temporary files with header or footer disappears, you will get the error message. It may happen, that you need to repeat step 4) above several times, usually not more than 3 - 5 times. Or if you generate about 150 pdf's like I did in my rails application, about 30% will fail.

In summary - there is something wrong with the temporary file cleanup, because even closed temporary file should stay around if unlink is not done. Maybe it should be reported in rails or ruby forum, I am not sure. But currently all the wicked pdf functionality which relies on tempfile fails in about 30% of cases. Do not know how to fix it.