Frameworks · Updated 2026-12-03
Generate PDFs in Rails
This guide renders PDFs from a Rails app with a plain HTTP call. You send a template id and a hash of data to DevilPDF and get back the PDF bytes or a link. Nothing to install on your servers: no wkhtmltopdf binary, no headless Chrome, no font packages.
The free plan includes 500 documents a month.
#1. Store the key
Sign up and create a key under API keys. Put it in your encrypted credentials:
bin/rails credentials:editdevilpdf:
api_key: dp_live_...Read it with Rails.application.credentials.dig(:devilpdf, :api_key). An environment variable such as ENV["DEVILPDF_API_KEY"] works just as well.
#2. A client with Net::HTTP
No gems needed. Put this in app/services/devil_pdf.rb:
require "net/http"
require "json"
class DevilPdf
ENDPOINT = URI("https://devilpdf.com/v1/render")
class Error < StandardError; end
# Returns the PDF bytes. Nothing is stored at DevilPDF.
def self.file(body)
request(body.merge(output: "file")).body
end
# Returns the document as a hash: "url", "id", "pages", "expires_at".
def self.document(body)
JSON.parse(request(body).body)
end
def self.request(body)
req = Net::HTTP::Post.new(ENDPOINT)
req["Authorization"] = "Bearer #{api_key}"
req["Content-Type"] = "application/json"
req.body = body.to_json
res = Net::HTTP.start(ENDPOINT.host, ENDPOINT.port, use_ssl: true, read_timeout: 60) do |http|
http.request(req)
end
return res if res.is_a?(Net::HTTPSuccess)
error = JSON.parse(res.body)["error"]
raise Error, "#{error['type']}: #{error['message']}"
end
def self.api_key
Rails.application.credentials.dig(:devilpdf, :api_key) || ENV.fetch("DEVILPDF_API_KEY")
end
endErrors always come back as JSON with an error object, which the client turns into an exception with the reason in the message.
#3. Send a PDF from a controller
class InvoicePdfsController < ApplicationController
def show
invoice = current_user.invoices.find_by!(number: params[:invoice_id])
pdf = DevilPdf.file(
template: "invoice",
filename: "invoice-#{invoice.number}",
data: {
number: invoice.number,
issue_date: invoice.issued_on.iso8601,
currency: invoice.currency,
customer: { name: invoice.customer_name, address: invoice.customer_address },
items: invoice.lines.map do |line|
{ name: line.description, quantity: line.quantity, unit_price: line.unit_price.to_f }
end,
tax_rate: 13,
tax_label: "HST"
}
)
send_data pdf, type: "application/pdf", disposition: "inline",
filename: "invoice-#{invoice.number}.pdf"
end
endRails.application.routes.draw do
resources :invoices, only: [] do
resource :pdf, only: :show, controller: "invoice_pdfs"
end
endGET /invoices/INV-1001/pdf now returns the PDF. Scoping the lookup to current_user keeps one customer from fetching another's invoice. unit_price.to_f matters if the column is a decimal: BigDecimal#to_json produces a string, and while the template still calculates with it, a number is cleaner.
The invoice starter adds up the items, tax and total for you. Fetch GET /v1/templates/invoice to see every field it accepts. The other starters are quote, receipt, statement, report, packing-slip and certificate.
#With Faraday
If your app already uses Faraday (2.x, which encodes and parses JSON without extra middleware gems):
require "faraday"
conn = Faraday.new(url: "https://devilpdf.com") do |f|
f.request :authorization, "Bearer", -> { ENV.fetch("DEVILPDF_API_KEY") }
f.request :json
f.response :raise_error
f.options.timeout = 60
end
res = conn.post("/v1/render", { template: "receipt", data: { number: "R-10482" }, output: "file" })
File.binwrite("receipt.pdf", res.body)#Attach it in Active Storage or a mailer
Render in a background job so checkout stays fast, then attach the bytes:
class ReceiptPdfJob < ApplicationJob
queue_as :default
def perform(order)
pdf = DevilPdf.file(template: "receipt", locale: order.locale, data: order.receipt_data)
order.receipt_pdf.attach(
io: StringIO.new(pdf),
filename: "receipt-#{order.number}.pdf",
content_type: "application/pdf"
)
end
endreceipt_data stands for your own method that builds the hash. In a mailer, attachments["receipt.pdf"] = pdf does the same for email.
#Other languages
Set locale and the starter's labels, dates and money switch. ar, he, fa and ur mirror the layout right to left, and fonts for every script are included.
DevilPdf.file(
template: "invoice",
locale: "ar",
data: { number: "INV-1002", currency: "SAR",
items: [{ name: "استشارات", quantity: 3, unit_price: 1250 }] }
)