Frameworks · Updated 2026-12-03
Generate PDFs in Go
This guide renders PDFs from Go with the standard library. You send a template id and your data to one endpoint and get back a link or the file itself. There is no browser to run and no cgo, so the binary stays small and runs anywhere Go does.
You need Go 1.22 or later and a DevilPDF API key. The free plan includes 500 documents a month.
#1. Get an API key
Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Keep it in an environment variable or your secrets manager, never in code you commit:
export DEVILPDF_API_KEY="dp_live_..."#2. Render an invoice and get a link
Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. This renders the invoice starter:
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
func main() {
payload := map[string]any{
"template": "invoice",
"data": map[string]any{
"number": "INV-1001",
"issue_date": "2026-12-03",
"due_date": "2027-01-02",
"company": map[string]any{"name": "Northwind Studio", "address": "410 Bay Street\nToronto, ON M5H 2Y4"},
"customer": map[string]any{"name": "Acme Robotics Inc.", "address": "2200 Mission Street\nSan Francisco, CA 94110"},
"items": []map[string]any{
{"name": "Brand identity system", "quantity": 1, "unit_price": 4800},
{"name": "Front-end development", "description": "Billed hourly", "quantity": 46, "unit_price": 135},
},
"tax_rate": 13,
"tax_label": "HST",
},
"filename": "INV-1001",
}
body, err := json.Marshal(payload)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest(http.MethodPost, "https://devilpdf.com/v1/render", bytes.NewReader(body))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("DEVILPDF_API_KEY"))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 60 * time.Second}
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
var doc struct {
ID string `json:"id"`
URL string `json:"url"`
Pages int `json:"pages"`
Error *struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.NewDecoder(res.Body).Decode(&doc); err != nil {
log.Fatalf("decode response (status %d): %v", res.StatusCode, err)
}
if doc.Error != nil {
log.Fatalf("%s: %s", doc.Error.Type, doc.Error.Message)
}
if res.StatusCode != http.StatusOK {
log.Fatalf("unexpected status %d", res.StatusCode)
}
fmt.Println(doc.URL, doc.Pages)
}Run it with go run main.go. The response is a document object with an id, the page count in pages, and a signed download link in url. The template adds up the line items, tax and total itself, so you never send totals.
To see every field a starter accepts, fetch it and read sample_data:
curl https://devilpdf.com/v1/templates/invoice \
-H "Authorization: Bearer $DEVILPDF_API_KEY"#3. Get the PDF bytes and save them
Add "output": "file" and the response body is the PDF itself. Nothing is stored on DevilPDF's side. Put this function in its own file so the next steps can reuse it:
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
var client = &http.Client{Timeout: 60 * time.Second}
// renderPDF sends body to /v1/render and returns the PDF bytes.
func renderPDF(ctx context.Context, body map[string]any) ([]byte, error) {
body["output"] = "file"
payload, err := json.Marshal(body)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://devilpdf.com/v1/render", bytes.NewReader(payload))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("DEVILPDF_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Type string `json:"type"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
return nil, fmt.Errorf("devilpdf: status %d", res.StatusCode)
}
return nil, fmt.Errorf("devilpdf: %s: %s", e.Error.Type, e.Error.Message)
}
return io.ReadAll(res.Body)
}Then call it and write the file:
package main
import (
"context"
"fmt"
"log"
"os"
)
func main() {
pdf, err := renderPDF(context.Background(), map[string]any{
"template": "receipt",
"data": map[string]any{
"number": "R-10482",
"paid_at": "2026-12-03",
"company": map[string]any{"name": "Lumen Cycle Works"},
"customer": map[string]any{"name": "Jordan Alvarez"},
"payment": map[string]any{"method": "Visa", "last4": "4242"},
"items": []map[string]any{
{"name": "Full tune-up", "quantity": 1, "unit_price": 129},
},
},
})
if err != nil {
log.Fatal(err)
}
if err := os.WriteFile("receipt.pdf", pdf, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("Saved receipt.pdf (%d bytes)\n", len(pdf))
}Run both files with go run .. Errors still come back as JSON, so check the status before you treat the body as a file. The devilpdf-document-id and devilpdf-pages response headers identify the document in your log.
#4. Serve it from a net/http handler
A handler that returns a PDF to the browser. The API key stays on the server. Replace main.go with this and keep devilpdf.go next to it. The route pattern uses the method and path wildcards that Go 1.22 added to http.ServeMux.
package main
import (
"fmt"
"log"
"net/http"
)
func invoicePDF(w http.ResponseWriter, r *http.Request) {
number := r.PathValue("number")
order, ok := loadOrder(number)
if !ok {
http.NotFound(w, r)
return
}
pdf, err := renderPDF(r.Context(), map[string]any{
"template": "invoice",
"data": order,
"filename": "invoice-" + number,
})
if err != nil {
log.Print(err)
http.Error(w, "could not render invoice", http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="invoice-%s.pdf"`, number))
w.Write(pdf)
}
// Replace with your database lookup.
func loadOrder(number string) (map[string]any, bool) {
return map[string]any{
"number": number,
"customer": map[string]any{"name": "Acme Robotics Inc."},
"items": []map[string]any{
{"name": "Consulting", "quantity": 3, "unit_price": 150},
},
}, true
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /invoices/{number}", invoicePDF)
log.Fatal(http.ListenAndServe(":3000", mux))
}Open http://localhost:3000/invoices/INV-1001 and the invoice shows in the browser. Passing r.Context() to renderPDF cancels the call if the visitor closes the page.
#Gin
The same route in Gin. Install it with go get github.com/gin-gonic/gin, then swap the handler and main:
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/invoices/:number", func(c *gin.Context) {
number := c.Param("number")
order, ok := loadOrder(number)
if !ok {
c.AbortWithStatus(http.StatusNotFound)
return
}
pdf, err := renderPDF(c.Request.Context(), map[string]any{
"template": "invoice",
"data": order,
})
if err != nil {
log.Print(err)
c.JSON(http.StatusBadGateway, gin.H{"error": "could not render invoice"})
return
}
c.Header("Content-Disposition", fmt.Sprintf(`inline; filename="invoice-%s.pdf"`, number))
c.Data(http.StatusOK, "application/pdf", pdf)
})
log.Fatal(r.Run(":3000"))
}Keep loadOrder from step 4 in the package. In chi, the handler from step 4 works as it is: register it with r.Get("/invoices/{number}", ...) and read the number with chi.URLParam(r, "number").
#5. Any language, same code
Add locale and the starter's labels, dates and money switch language. Arabic, Hebrew, Persian and Urdu also flip the page right to left. Fonts for every script are loaded for you.
pdf, err := renderPDF(ctx, map[string]any{
"template": "invoice",
"locale": "ar",
"data": map[string]any{
"number": "INV-1002",
"currency": "SAR",
"customer": map[string]any{"name": "شركة الأفق للتجارة"},
"items": []map[string]any{
{"name": "استشارات", "quantity": 3, "unit_price": 1250},
},
},
})See languages and locales for the full list.
#Many documents at once
A render normally takes well under a second, so calling it inside a request is fine. For hundreds of PDFs, do not loop over /v1/render and wait on each one, even from goroutines. Send them to POST /v1/render/batch in one request and get a webhook when they finish. Batch documents are always stored and returned as links. See async and batch.
If you do retry single renders, retry only rate_limited, render_timeout, internal_error, or a render_error with "retryable": true. Everything else fails the same way until the request changes. See errors.
#Next steps
- Render reference: every field
/v1/renderaccepts. - Templates: copy a starter and make it yours.
- Generate PDFs in Node.js and in Python.
- Get a free API key