How to generate a PDF from HTML in Ruby on Rails
Published 2 min read
In Rails, turning HTML into a PDF often means adding a gem that wraps a rendering binary, then installing that binary and keeping it working in development, in CI and in production. With an API it is one HTTP request, and Ruby’s standard library already makes it. This guide shows a small class and a controller that sends the file, with the rustedf.cloud API.
A small class on Net::HTTP
require "net/http"require "json"
class RustedfPdf class Error < StandardError; end
ENDPOINT = URI("https://api.rustedf.com/v1/render")
def self.render(template_id:, data:, locale: "en-US") request = Net::HTTP::Post.new( ENDPOINT, "Authorization" => "Bearer #{Rails.application.credentials.dig(:rustedf, :key)}", "Content-Type" => "application/json" ) request.body = { template_id: template_id, locale: locale, data: data }.to_json
response = Net::HTTP.start(ENDPOINT.host, ENDPOINT.port, use_ssl: true, read_timeout: 40) do |http| http.request(request) end
return response.body if response.is_a?(Net::HTTPSuccess)
raise Error, error_message(response) end
def self.error_message(response) JSON.parse(response.body).dig("error", "message") || "Render failed (#{response.code})" rescue JSON::ParserError "Render failed (#{response.code})" endendA successful response is the PDF itself, so response.body is the file. On a failure the body is
JSON with a stable code and a message.
Keep the key in the encrypted credentials (bin/rails credentials:edit) or in an environment
variable, never in a view or in the browser. Set the read timeout above the time limit of your
plan, so your request does not give up before the service does.
A controller that sends the PDF
class InvoicesController < ApplicationController def show invoice = Invoice.find_by!(number: params[:number])
pdf = RustedfPdf.render( template_id: Rails.configuration.x.rustedf_invoice_template, locale: "en-US", data: { number: invoice.number, customer: { name: invoice.customer.name }, total: invoice.total.to_s } )
send_data pdf, type: "application/pdf", disposition: "inline", filename: "invoice-#{invoice.number}.pdf" rescue RustedfPdf::Error => error Rails.logger.error(error.message) head :bad_gateway endendget "invoices/:number", to: "invoices#show", constraints: { number: /[\w-]+/ }To send HTML instead of a saved template id, use html: in place of template_id:. Pass anything a
user typed through data, not inside the HTML string: values in data are escaped, and the HTML
itself is read as a template. If you render a view to a string first, remember that the result is
treated as a template again.
Retry when the service is busy
A 429 (rate limit) or a 503 (busy) carries a Retry-After header. A failed render costs no
credit, so retrying is safe: read response["Retry-After"], sleep for that many seconds and send
the request again, a limited number of times. For work that does not need to answer the browser at
once, run the call in a background job and retry there.
Errors worth handling
| Status | code |
What to do |
|---|---|---|
| 401 | unauthorized |
The key is missing, wrong or revoked. |
| 402 | insufficient_credits |
No credits left. Nothing was rendered. |
| 422 | invalid_template |
The template or its data failed. Read message. |
| 429 | rate_limited |
Wait for Retry-After and retry. |
| 503 | busy |
The service is busy. Wait for Retry-After and retry. |
| 504 | render_timeout |
The document took longer than your plan allows. |
Run POST /v1/validate with the same body while you build the template: it lists anything the
service did not fully support, without returning the PDF or using a credit.
Read Rendering a PDF, Authentication and Errors and limits.
Keep reading
Code and integrations
Generate a PDF in ASP.NET Core: MVC, Razor Pages and minimal APIs
Turn a Razor view into a PDF in ASP.NET Core with one API call: a view renderer, a print-ready view, an MVC action, a Razor Pages handler and the traps to avoid.
3 min read
Code and integrations
Convert a web page to PDF in C# without a headless browser
Fetch a page with HttpClient and turn its HTML into a PDF with one API call in C#. Which pages this suits, which it does not, and how to check before you rely on it.
3 min read
Code and integrations
C# PDF report generator: a paged table with totals and page numbers
Build a PDF report in C# from a list of objects: a table whose header repeats on every page, a total, page numbers and the page count, with one HTTP call.
3 min read
Code and integrations
Save a PDF in C#: to disk, as a download or in blob storage
Save the PDF returned by a render call in C#: write it to disk, send it as a download from ASP.NET Core, keep a signed link or upload it, and avoid saving an error.
2 min read