Skip to content

Guide · Ruby

Generate a PDF invoice from JSON in Ruby

Your Ruby code sends the facts of an invoice (customer, lines, VAT rate) and gets back a finished PDF. Sums, number formats, the due date and the payment QR code are the template’s job, so none of that logic ends up in your application.

Free plan with 100 units a month, no credit card

What you need

  • An API key. Create one in the app under API keys and export it as FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start.
  • Ruby. You need Ruby 3; the program uses net/http and json from the standard library.
  • The template. invoice-de from the invoice example: copy it into your workspace from the example’s page, which keeps the name invoice-de and publishes the copy, or push the folder with the CLI (formfeed templates push --publish). A render uses the published version.
  • The data. The example’s data.json next to the program. It holds the company, the customer and two invoice lines, and no totals.

The program

The program reads data.json, posts it with the template’s name and a file name built from the invoice number, waits for the result when the API answers 202, stops with the API’s message when something is wrong, and saves the PDF.

render.rbRuby
require "json"
require "net/http"

data = JSON.parse(File.read("data.json"))
body = {
  template: "invoice-de",
  data: data,
  filename: "invoice-#{data["invoice"]["number"]}.pdf",
}
auth = { "Authorization" => "Bearer #{ENV.fetch("FORMFEED_API_KEY")}" }

response = Net::HTTP.post(
  URI("https://api-eu.formfeed.dev/v1/renders"),
  JSON.generate(body),
  auth.merge("Content-Type" => "application/json")
)
render = JSON.parse(response.body)

# not done within 60 seconds: the answer is 202 and the render goes on in the background;
# its result answers the same way until the render has finished
while response.code == "202"
  sleep 2
  response = Net::HTTP.get_response(URI("https://api-eu.formfeed.dev/v1/renders/#{render["id"]}/result"), auth)
  render = JSON.parse(response.body)
end

# every error is a problem document (RFC 9457) with a title and a detail
abort "#{render["title"]}: #{render["detail"]}" unless response.is_a?(Net::HTTPSuccess)

File.binwrite("invoice.pdf", Net::HTTP.get(URI(render["download_url"])))
puts "#{render["id"]} #{render["page_count"]} page(s), #{render["units"]} unit(s)"

Run it

It prints the render’s id, the page count and the units it cost, and invoice.pdf lies next to the program. With a key that starts with ff_test_ the render is not metered; on the Free plan it carries a small watermark.

Shell
export FORMFEED_API_KEY=ff_test_...
ruby render.rb

What is particular about Ruby

  • Hashes become JSON. Symbol keys are fine: JSON.generate writes them as strings, and the API’s snake_case names are idiomatic Ruby anyway.
  • abort with the problem. A problem document carries a title and a detail; the program prints both and exits with status 1.
  • In Rails. Put the call in a job (Active Job, Sidekiq), not in the request cycle: a synchronous render answers when the PDF is done, which can take up to 60 seconds before the API answers 202 and finishes in the background.

What the template does with the JSON

The request carries no derived numbers, which is the point of rendering from a template:

  • Totals. invoice.lines | sum('total') adds the lines, and VAT and gross follow from invoice.vat_rate.
  • Formats. With the template’s locale de-DE, money prints 3.760,40 € and date('dd.MM.yyyy') prints 10.09.2026; dateAdd(14, 'days') sets the due date.
  • GiroCode. epcQr draws the SEPA payment code from name, IBAN, BIC, amount and reference.
  • File name. is not the template’s job. The API takes filename as written and fills in no template expressions, so the program builds invoice-2026-0042.pdf from the invoice number, and the download carries that name. Characters outside A–Z, a–z, 0–9, ., -, _, (, ) and the space become _.

From one invoice to many

An invoice run is a batch: one request with up to 1,000 documents, one zip at the end, and a webhook when it is done. See batches. For documents that take longer than a few seconds, render asynchronously and let a webhook report back.

When the API says no

  • One shape for every error. Errors are problem documents (RFC 9457) with type, title, status, detail, a stable code and the request_id to quote to support; the type URL leads to a page about that error. The list is in the error reference.
  • The usual ones. 401 unauthorized for a missing or revoked key, 404 template_not_found for a wrong template name, 422 template_runtime_error when the template fails on the data, 429 rate_limited above the plan’s requests per second, 402 quota_exceeded when the Free plan’s units are used up (a paid plan bills extra units up to its hard cap).
  • Retry safely. Send an Idempotency-Key header with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.

The job around this program

This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Invoice PDF API.

More Ruby guides

FAQ

Can I send the invoice HTML instead of using a stored template?
Yes, put it in html and leave template out; the HTML-to-PDF guide of this language shows it. A stored template adds versions, a preview with your sample data and release channels.
How long is the download URL valid?
A signed link is valid for at most seven days and never longer than the file is kept, which your plan’s retention decides (a workspace setting or expires_in can only shorten it). GET /renders/{id} issues a fresh link at any time, so store the render’s id, not the URL. With access: "public" the link lasts as long as the file. Details in the rendering docs.
What does a render cost?
One unit for every started five pages of a PDF, so one to five pages cost one unit and six to ten cost two. Test renders are free. See pricing.

PDF invoice from JSON in other languages

Start rendering today

The free plan includes 100 units a month and free test renders. Change plans when you need more.