To generate a PDF from HTML in a Ruby on Rails application, you can use the Wicked PDF
gem. Wicked PDF is a popular gem that allows you to convert HTML and CSS into PDF documents using the wkhtmltopdf
command-line tool. Here's how you can set it up:
Step 1: Install the wkhtmltopdf
binary
Before using the Wicked PDF
gem, you need to install the wkhtmltopdf
binary on your system. You can find installation instructions on the wkhtmltopdf
website: https://wkhtmltopdf.org/
Step 2: Add the Wicked PDF
gem to your Gemfile
Open your Rails project's Gemfile
and add the following line:
rubygem 'wicked_pdf'
Then run bundle install
to install the gem.
Step 3: Configure Wicked PDF
Create an initializer file (e.g., wicked_pdf.rb
) in the config/initializers
directory with the following content:
rubyWickedPdf.config = {
exe_path: '/path/to/your/wkhtmltopdf' # Replace this with the path to your wkhtmltopdf binary
}
Replace '/path/to/your/wkhtmltopdf'
with the actual path to the wkhtmltopdf
binary on your system.
Step 4: Create a PDF template (HTML file) Create an HTML file that you want to convert into a PDF. You can use Rails views or any other HTML template engine (e.g., ERB, HAML, Slim).
For example, you could have a view file pdf_template.html.erb
in your app/views
directory:
erb<!DOCTYPE html> <html> <head> <title>My PDF</title> </head> <body> <h1>Hello, this is my PDF!</h1> <!-- Your content goes here --> </body> </html>
Step 5: Generate the PDF in your controller
In your Rails controller, you can use the render
method with the pdf
option to generate the PDF from the HTML template:
rubyclass PdfController < ApplicationController
def generate_pdf
respond_to do |format|
format.html
format.pdf do
render pdf: 'my_pdf_file_name' # This will generate a PDF named "my_pdf_file_name.pdf"
end
end
end
end
Step 6: Create a route for the PDF generation
Finally, create a route in your config/routes.rb
file to map the PDF generation action:
rubyRails.application.routes.draw do
get 'generate_pdf', to: 'pdf#generate_pdf'
end
Now, if you access the URL /generate_pdf.pdf
, it will render the HTML template as a PDF using the Wicked PDF
gem.
Remember to customize the HTML template according to your requirements, and you can use CSS to style the PDF output.