Creating Printable Webpages

Creating a printable version of a website page is far harder than it would seem.

Tags: Rails, Setup, Ruby on Rails

Back to Blogs

This uses the following gems (don't forget to bundle install):

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary-edge', '~> 0.12.2.1'
gem 'wkhtmltopdf-heroku', '2.12.5.0'

Then run the initializer:

rails generate wicked_pdf

And add your wicked_pdf.rb initializer:

WickedPdf.config ||= {}
WickedPdf.config.merge!({
  # your extra configurations here
})

Add the pdf-y goodness to your controller (this is articles#show, but it can be whatever you want):

def show
    respond_to do |format|
      format.html
      format.pdf do
        @pdf = true
        render pdf: @article.title,
           disposition: 'attachment',
           template: 'articles/show.html.erb',
           page_size: 'Letter',
           encoding:"UTF-8"
      end
    end
end

And add your link on the view:

<%= link_to "Download PDF Version", { :action => "show", :format => :pdf }, target: '_blank' %>

And I add some conditional on-page CSS for prettification purposes:

<% if @pdf %>
  <style>
    h1 {
      text-align: center;
      font-size: 32px;
      font-family: roboto;
      font-weight: 200;
    }

    img {
      display: block;
      max-width: 300px;
      max-height: 300px;
      margin-left: auto;
      margin-right: auto;
      box-shadow: 0 8px 17px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19) !important;
    }

    p {
      font-family: roboto;
      font-size: 12px;
    }

    small {
      color: #787878;
    }

    h2 {
      color: #b15eeb;
      font-weight: 700;
      font-family: roboto;
      font-size: 24px;
    }

    .text-center {
      text-align: center;
    }
  </style>
<% end %>

Back to Blogs