GENERATE PDF FILE IN RAILS

Code Generating PDFs From HTML With Rails

Using Wicked_pdf with Rails 5

Step 1

Install the required gems

gem 'wicked_pdf', '~> 1.1'  
gem 'wkhtmltopdf-binary'   

then generate the initializer

rails g wicked_pdf              

Step 2(optional)

You need to register the pdf mime type. This is done in the initializer. This is required for older rails version only

#config/initializers/mime_types.rb

Mime::Type.register "application/pdf", :pdf

Step 3

Setup the controller to render pdf format. In this setup you have the options to configure so many item depends on you requirement. At the moment, only a few items need to be setup for me.

#controllers/yours_controller.rb

def show
   .
   .
   .
   respond_to do |format|
    format.html
    format.pdf do
      render pdf: "Your_filename",
      template: "yours_controller/show.html.erb"
      layout: 'pdf'

    end
   end
end

Step 4

Create and setup the view part of the application

First we create the the new layout for the pdf to use and use the helper from wicked_pdf to make reference to the stylesheet, javascript library or image required. For this example, I will only use the stylesheet helper

#app/views/layouts/pdf.html.erb

<!DOCTYPE html>
<html>
<head>
<title>PDF</title>
  <%= wicked_pdf_stylesheet_link_tag "application" -%>
</head>
<body>

  <div class='container'>
    <%= yield %>
  </div>

</body>
</html>


I my case the css or scss file name is “application”

Next, we can create the link to generate the pdf file

<%= link_to 'Create PDF document', youritem_path(@youritem, :format => :pdf) %>
Post a Comment

Popular posts from this blog

RAILS: UPLOADING PHOTOS VIA AMAZON S3 AND PAPERCLIP (UPLOADING FILES TO S3 IN RUBY WITH PAPERCLIP)

CARRIERWAVE - UPLOAD ANY MEDIA (AUDIO , VIDEO AND IMAGE ) FILE IN RAILS

SELECT COUNTRY WITH STATE AND IT'S CITIES RAILS

UNINITIALIZED CONSTANT PAPERCLIP::STORAGE::S3::AWS

CREATE API FOR USER SIGN UP, LOGIN AND CREATE PUBLISHER WITH CURRENT USER

HOW TO CALL RAILS API FROM SIMPLE HTML PAGE.

Building native extensions. This could take a while... ERROR: Error installing mysql: ERROR: Failed to build gem native extension.