rustedf.cloud
Menu

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

app/services/rustedf_pdf.rb
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})"
end
end

A 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

app/controllers/invoices_controller.rb
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
end
end
config/routes.rb
get "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.

← All posts