Generating PDFs from HTML with variables in Ruby/Rails
We are refactoring our PDF generator in our app and are looking at alternatives to the hacked up one we use now. After some research, it seems Prawn or PDFKit is the way to go.
Ideally, we would like to have a HTML to PDF conversion but also include some fields that get filled out through Ruby, say
<h1>#{user.name}</h1>
So when the PDF is gen开发者_运维知识库erated, that is replaced with the user's name. Any suggestions on what to use/examples on how to do this?
Thanks.
Have you looked at Prince for PDF generation? I recently went through all the Prawn and PDFKits and whatnot, and found them just too..quirky..to use.
Prince takes straight HTML and outputs PDF. Very simple to use with Rails - you just make a template and run it through the Rails template system and spit it out to a file (or a pipe directly to Prince) instead of to the screen.
For example see render_to_string
in Rails. You can use that to save the rendered data into a file and feed it to Prince (or any other PDF generator you choose use).
Prince:
http://www.princexml.com/
Have a look at wkhtmltopdf (GitHub) -- it uses webkit to render so you tend to get fairly good results. It has some quirks (odd characters appearing in Adobe Reader when typefaces are rendered with ligatures for example), so test it for your use-cases before you decide to use it in production.
Of course, you would generate the HTMLs using the template language of your choice as you would any web-page.
精彩评论