How To Draw Images In Ruby On Rails
The best approach for generating PDFs in Track really depends on the types of PDFs yous demand to generate. This tutorial will provide step-past-stride instructions for generating PDFs past using wkhtmltopdf
, an open source CLI for rendering HTML into PDF from standard Rails view and mode code. This approach is ideal if you don't need a publishing workflow or precise control over page output.
For the purpose of this tutorial I've made a elementary demo application on Heroku to prove you what nosotros'll exist building. The awarding lists a series of sample invoices that can be previewed in the browser, and then converted to PDF. The source code is bachelor in our repo rails-generate-pdf
. Hither'south my configuration:
Rails 5.2.1 Postgresql ten.5 wkhtmltopdf 0.12.4 macOS Mojave 10.fourteen.ane
If yous're looking for more granular control over PDF output, wkhtmltopdf
may not be the best. Instead, Prawn is a pop open source pure Carmine PDF generation library that is reasonably performant and uses a Ten,Y coordinate system for placing elements on a page. The downside is you lot'll need time to wrap your caput around its rendering model, and acquire its DSL (Domain Specific Linguistic communication). Alternatively, you could utilize a commercial PDF generation library (similar PDFTron PDF SDK ).
Let's brainstorm!
Step i - Install wicked_pdf
Start by downloading and installing Wicked PDF'south precompiled binary. You lot can test the output by converting a URL into a PDF file past opening the command line and typing this:
wkhtmltopdf http://google.com google.pdf
This volition generate the file google.pdf
.
But, how do nosotros utilize this in our Scarlet on Runway projects?
Wicked PDF uses the trounce utility wkhtmltopdf
to serve a PDF file from HTML. Rather than dealing with a PDF generation DSL of some sort, you simply write an HTML view as you would usually do, so permit Wicked PDF have care of the hard stuff.
Step two - Create a New Ruby on Rails App
# control line - create Ruby on Track project rails new rails-generate-pdf –webpack=react –database=postgresql
Step iii – Add together and Install Dependencies
We will utilize Bootstrap iv for styling (which also requires jQuery) and wicked_pdf
for generationg PDF. Here we'll install the required gems:
# Gemfile # track-generate-pdf/Gemfile gem 'jquery-rails' gem 'bootstrap' , '~> 4.1.iii' gem 'wicked_pdf' gem 'wkhtmltopdf-binary'
Because wicked_pdf
is a wrapper for wkhtmltopdf
, we install that as well (gem wkhtmltopdf-binary
). Once all gems are added to track-generate-pdf/Gemfile
, run this from the root of your project:
# control line bundle install
Then generate the initializer:
# control line rails one thousand wicked_pdf
Step 4 – Annals the PDF MIME Type
For older rails versions, you'll demand to register the PDF MIME type in the initializer:
# file: rails-generate-pdf/config/initializer/mime_types.rb Mime::Type.register "application/pdf", :pdf
Step 5 - Create the Models
Our demo awarding will merely take two models: Invoice and InvoiceItem. To create the Invoice model, navigate to the root of your projection from the command line and type:
# command line -> generate Invoice Model rail generate model Invoice from_full_name from_address from_email from_phone to_full_name to_address to_email to_phone condition discount:decimal vat:decimal
Then open the Invoice model file (app/models/invoice.rb
) and add the following code:
# file: rails-generate-pdf/app/models/invoice.rb class Invoice < ApplicationRecord has_many :invoice_items , dependent: :destroy STATUS_CLASS = { :typhoon = > "bluecoat bluecoat-secondary" , :sent = > "badge badge-chief" , :paid = > "badge badge-success" } def subtotal cocky .invoice_items.map { |item| item.qty * particular.price } .sum cease def discount_calculated subtotal * ( self .discount / 100.0 ) end def vat_calculated (subtotal - discount_calculated) * ( self .vat / 100.0 ) end def total subtotal - discount_calculated + vat_calculated end def status_class STATUS_CLASS [ self .status.to_sym] end end
Next, create the InvoiceItem model using the command line (in the root of your projection):
# control line -> generate InvoiceItem Model rails generate model InvoiceItem name clarification price:decimal qty:integer invoice:references
At present open the InvoiceItem model file (app/models/invoice_item.rb
) and add the following code:
# file: rails-generate-pdf/app/models/invoice_item.rb class InvoiceItem < ApplicationRecord belongs_to :invoice terminate
Next, create your database and tables by running these commands:
# command line -> run commands rake db:create rake db:migrate
Step half dozen – Create a Controller and Setup Routes
First generate the controller by running this command:
# command line -> run control rails generate controller Invoices index show
Next, open your controller file (app/controllers/invoices_controller.rb
) and add the post-obit code (which will return page contents into PDF format):
# file: rails-generate-pdf/app/controllers/invoices_controller.rb class InvoicesController < ApplicationController def index @invoices = scope end def show @invoice = scope. discover (params[ :id ] ) respond_to do |format| format.html format.pdf do render pdf: "Invoice No. #{@invoice.id} " , page_size: 'A4' , template: "invoices/show.html.erb" , layout: "pdf.html" , orientation: "Landscape" , lowquality: truthful , zoom: 1 , dpi: 75 stop stop end individual def telescopic : : Invoice .all. includes ( :invoice_items ) terminate finish
Yous'll discover we have two deportment in our controller:
-
index
: shows a list of all invoices -
show
: previews a single invoice
The prove
activeness has 2 formats (html
and pdf
), which volition exist used to ascertain how the content is rendered. For example, if you access the invoice directly without the .pdf
extension, you'll see an HTML preview, while adding the .pdf
extension will return it to PDF. Endeavor it here:
- http://rails-generate-pdf.herokuapp.com/invoices/1
- http://track-generate-pdf.herokuapp.com/invoices/one.pdf
You tin configure the options even so you lot need (see wkhtmltopdf
documentation for additional details). To customize the layout of the PDF, use the following settings:
- template (
invoices/evidence.html.erb
): defines the template to exist used when rendering the pdf - layout (
pdf.html.erb
): defines the main application layout
(These files are available in our repo.)
Once you're happy with the layout, open your routes file (app/config/routes.rb
) and add the following code:
# file: runway-generate-pdf/app/config/routes.rb Rail .awarding.routes.depict do root to: 'invoices#index' resources :invoices , only: [ :index , :bear witness ] end
Stride vii - Setup the View Part of the Application
First we need to create the new layout and employ the helper from wicked_pdf to reference the stylesheet, JavaScript, or image assets. For this case, I volition but use the stylesheet helper:
# file: track-generate-pdf/views/layotus/pdf.html.erb <!DOCTYPE html> <html> <caput> <title>PDFs - Ruby on Rails</title> <%= wicked_pdf_stylesheet_link_tag "invoice" %> </head> <trunk> <%= yield %> </trunk> </html>
In this example the css or scss file proper noun is "invoice" (app/assets/stylesheets/invoice.scss
).
At present you need to brand sure all the assets will are precompiled (according to the official GitHub, this next step is essential for your gem to work perfectly when you deploy to production):
# file: config/initializers/avails.rb Rails .application.config.assets.precompile + = %w( invoice.scss )
The to a higher place array volition need to include every stylesheet and JavaScript library that you're using.
Adjacent, nosotros need to add together a link to the invoice page for generatingto generate the PDF by pointing to the show
action of the invoice controller, and using the pdf
format (/invoices/:id.pdf)
):
# file rails-generate-pdf/app/views/layouts/shared/_header.html.erb # invoice_path(@invoice, format: :pdf) -> /invoice/1.pdf < % = link_to 'DOWNLOAD PDF', invoice_path ( @invoice , format: :pdf ) % >
And that'due south information technology! Y'all can now deploy your awarding for generating PDFs. Here's our demo application that we deployed to a free Heroku web dyno.
Here's how the index looks like:

Here's how the PDF of the invoice looks similar:

Determination
Using wkhtmltopdf
is a quick and easy mode to generate PDFs from Ruby. However, if y'all need to generate PDFs from something other than HTML, want to integrate this into a workflow, or need precise control over positioning, so you're out of luck with wkhtmltopdf
.
Additionally, wkhtmltopdf
is based on the QtWebKit rendering engine, which is based on Apple'southward WebKit (which is a fork of KDE'due south KHTML). These engines are best suited for simple documents where you tin can afford to have some inconsistencies or failures.
If y'all need more reliability and robust functionality PDFTron's Red PDF library offers PDF generation and many additional features. You lot tin get started with a costless trial and and then bank check out some of the Reddish code samples to help get you upward and running quickly.
If you have whatever questions near PDFTron's PDF SDK, delight feel free to arrive touch !
You can notice the source lawmaking for this weblog post at our GitHub runway-generate-pdf
.
Source: https://www.pdftron.com/blog/rails/how-to-generate-pdf-with-ruby-on-rails/
Posted by: hassourprive.blogspot.com
0 Response to "How To Draw Images In Ruby On Rails"
Post a Comment