wicked_pdf tips&tricks

wicked_pdf tips&tricks

In the project I am developing there is a need to generate a PDF with different data (PDF is very popular in Germany).

There is a couple of Ruby gems for this job, all of them are good, but one is the best - wicked_pdf. It has great documentation with examples, but sometimes generated PDFs look weird or event broken, with no errors appearing during generation.

Here are some tricks what to do if a PDF is broken.

How to generate a PDF in a model

As you can see from documentation, wicked_pdf is supposed to be used in controllers most of the time, because it relies on Rails rendering system. What to do if you want to render a PDF in a model (for invoice generation, for example)? First of all, there is a method pdf_from_string for WickedPdf object, which can generate a PDF from a string.

To generate such a string from templates there is ApplicationController::Renderer module with method render which can be used in models (Rails 5) like this:

def render(template, options = {})
    template: template,
    layout: “layout.pdf.erb”,
    locals: { object: @object },

WickedPdf.new.pdf_from_string(render(“template_name”), {})
Pass footer / header as a separate template for a PDF

Sometimes there is a need to generate multiple pages with the same footer / header for it. It can be done by passing hash options to pdf_from_string method

options = {
  footer: {
    content: render(“footer_template”)

WickedPdf.new.pdf_from_string(render(“template_name”), options)

But here is one thing: footer / header templates should be valid HTML documents with all the proper tags. Miss html or body tag - and you get a broken PDF.

Some elements do not appear in a PDF

All templates are fine, tags are in their places but some elements are missing in the generated PDF. What’s wrong? CSS styles might be the problem.

For example: never ever use

height: 100%;

in your style for a PDF. In that case all you content will be spread across multiple empty PDF pages.

Another possible issue:

position: absolute;
left: 800px;

In this case an element will be rendered outside of a visible PDF page ¯\(ツ)

Wrap up

wicked_pdf is a great gem for PDF generation, it has good documentation and good API for template management. But sometimes something goes wrong and no errors appear. What to do in that case? Check your script / application on other machines, a colleague's one or CI for example, wkhtmltopdf might be the reason.