If you're deploying your app to somewhere where you can't be sure to have reliable disk read/write access, the normal strategy of writing to a temp-file doesn't work.
Instead we can open a pipe to the Phantom.js process, and then pass in the HTML via stdin
, and then have the rasterize.js
script write out the resulting PDF to stdout
, which we can then capture.
Any log messages from the Phantom.js process can be passed via stderr
if we want.
If we're using the default Rails setup for session handling, i.e. a _session_id
cookie, we can just pass in the session ID and have the rasterize.js
script fake a session cookie.
We can provide some additional configuration for the Phantom.js process using a config.json
file.
(I can't remember exactly why we set the things as we did, but some of them were needed.)
Hi @Sri-K
I can see that the source files here are a bit short on context. I'll try to elaborate a bit:
All the files are in my example locates in
/lib/phantomjs/
under the Rails root.The idea is that you call
Phantomjs.pd(html, request)
wherehtml
is a string containing the HTML contents of a page, andrequest
is anActionDispatch::Request
instance.It is assumed that the HTML is something that would otherwise have been the response for some URL, so there might be relative references in the HTML to e.g. images. Because of this, we need to pass the URL to Phantomjs. Also, as additional resources needed for the rendering might be protected by authorisation or otherwise be session dependent, we also need to be able to generate a session cookie. Both the session-id and URL can be found on the
request
object, and that's why we pass that to thePhantomjs.pdf()
method.Notice: This has nothing to do with the Prawn gem, which is another approach to PDF generation. See https://github.com/prawnpdf/prawn#should-you-use-prawn
This is more an alternative to Wicked-PDF, which we were using but had some issues with at the time. There might be better options available today for converting HTML to PDF in Ruby.