Search code examples
ruby-on-railswkhtmltopdftemporary-filesqpainter

Cannot write to temp files using wkhtmltopdf in Rails


I'm using Terrapin to execute wkhtmltopdf from command line inside Rails.

Terrapin::CommandLine.path = "/usr/bin/wkhtmltopdf"
pdfCommand = Terrapin::CommandLine.new("xvfb-run wkhtmltopdf :html_source :pdf_target")
tempHTML = Tempfile.new(["pattern", ".html"])
tempHTML << html
tempPDF = Tempfile.new(["pattern",".pdf"])
pdfCommand.run(html_source: tempHTML.path, pdf_target: tempPDF.path)

It runs, but returns:

QPainter::begin(): Returned false
Error: Unable to write to destination
Exit with code 1, due to unknown error.

I've made sure wkhtmltopdf has full permissions, I'm not sure if maybe Terrapin has something to do with this?

Edit: running xvfb-run wkhtmltopdf http://www.example.com test.pdf in console works as expected.


Solution

  • In order for Terrapin to process the interpolations, they need to be in the second argument to new. Ie. it expects the command you're running to be separate from the string with the interpolations in it:

    Terrapin::CommandLine.new("xvfb-run", "wkhtmltopdf :html_source :pdf_target")
    

    If you add Terrapin::CommandLine.logger = Logger.new(STDOUT) to your script you'll see that terrapin was trying to run, literally, xvfb-run wkhtmltopdf :html_source :pdf_target.