Guide · Go
Generate a PDF invoice from JSON in Go
Your Go 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. - Go. You need Go 1.21 or newer; the program uses the standard library only.
- The template.
invoice-defrom the invoice example: copy it into your workspace from the example’s page, which keeps the nameinvoice-deand 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.jsonnext 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.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const endpoint = "https://api-eu.formfeed.dev/v1/renders"
// a render or a problem document: both are JSON objects, so one struct decodes either
type render struct {
ID string `json:"id"`
Status string `json:"status"`
DownloadURL string `json:"download_url"`
PageCount int `json:"page_count"`
Units float64 `json:"units"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// send makes one call with the key and decodes the answer
func send(method, url string, body []byte) (int, render) {
request, _ := http.NewRequest(method, url, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+os.Getenv("FORMFEED_API_KEY"))
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
var answer render
json.NewDecoder(response.Body).Decode(&answer)
return response.StatusCode, answer
}
func main() {
data, err := os.ReadFile("data.json")
if err != nil {
panic(err)
}
// the file name carries a value of the data, so that one value is decoded
var parsed struct {
Invoice struct {
Number string `json:"number"`
} `json:"invoice"`
}
if err := json.Unmarshal(data, &parsed); err != nil {
panic(err)
}
body, _ := json.Marshal(map[string]any{
"template": "invoice-de",
"data": json.RawMessage(data),
"filename": "invoice-" + parsed.Invoice.Number + ".pdf",
})
status, result := send("POST", endpoint, 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
for status == http.StatusAccepted {
time.Sleep(2 * time.Second)
status, result = send("GET", endpoint+"/"+result.ID+"/result", nil)
}
// every error is a problem document (RFC 9457) with a title and a detail
if status >= 400 {
fmt.Fprintf(os.Stderr, "%s: %s\n", result.Title, result.Detail)
os.Exit(1)
}
file, err := http.Get(result.DownloadURL)
if err != nil {
panic(err)
}
defer file.Body.Close()
out, _ := os.Create("invoice.pdf")
defer out.Close()
io.Copy(out, file.Body)
fmt.Printf("%s %d page(s), %v unit(s)\n", result.ID, result.PageCount, result.Units)
}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.
export FORMFEED_API_KEY=ff_test_...
go run main.goWhat is particular about Go
json.RawMessage. The sample data goes into the body as it is on disk, without being decoded into Go types first, so the program works for any template.- One struct for both answers. A render and a problem document are both JSON objects, so a single struct with
titleanddetailbeside the render fields decodes either. - Timeouts.
http.DefaultClienthas none. In a service, give the client aTimeouta little above 60 seconds: a synchronous render answers when the file is done, or after 60 seconds with202while it goes on 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 frominvoice.vat_rate. - Formats. With the template’s locale
de-DE,moneyprints3.760,40 €anddate('dd.MM.yyyy')prints10.09.2026;dateAdd(14, 'days')sets the due date. - GiroCode.
epcQrdraws the SEPA payment code from name, IBAN, BIC, amount and reference. - File name. is not the template’s job. The API takes
filenameas written and fills in no template expressions, so the program buildsinvoice-2026-0042.pdffrom 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 stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader 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 Go guides
FAQ
- Can I send the invoice HTML instead of using a stored template?
- Yes, put it in
htmland leavetemplateout; 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_incan only shorten it).GET /renders/{id}issues a fresh link at any time, so store the render’s id, not the URL. Withaccess: "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.