Generate PDFs in Go with Api2Pdf: html/template, net/http Streaming and Direct-to-S3 Uploads
Summary. Go has no built-in way to turn HTML into a PDF. The usual options each cost something: gofpdf and its forks draw PDFs primitive by primitive (and the original is archived), wkhtmltopdf wrappers depend on an archived WebKit engine, and chromedp or go-rod need a full Chromium next to your static binary, which undoes most of what makes Go deployments pleasant. This guide keeps the parts Go developers already like, html/template and net/http, and hands rendering to the Api2Pdf Headless Chrome endpoint. You will make a first call in one file, build a small dependency-free client with context-aware retries and a typed error, stream invoices from an HTTP handler, render a batch concurrently with errgroup and merge it into a password-protected packet, have Api2Pdf write PDFs straight into your own S3 bucket with useCustomStorage, and test all of it with httptest.
Using another stack? There are companion posts for Spring Boot, Ruby on Rails, Laravel, FastAPI and Next.js App Router.
The architecture in one paragraph
The API key lives in an environment variable or your secrets manager, never in the browser. Your service renders an html/template to a string and sends it to POST https://v2.api2pdf.com/chrome/pdf/html with the raw key in the Authorization header (no Bearer prefix). With ?outputBinary=true the response body is the PDF itself, which a handler can io.Copy to the http.ResponseWriter. Without it you get JSON with a FileUrl that Api2Pdf hosts for 24 hours plus a ResponseId; that is the form you chain into merge, password and watermark calls. If the PDF belongs in your own bucket, add useCustomStorage and a presigned URL and Api2Pdf uploads it there for you. Chrome never runs in your process or your container, so your binary stays a single static file on a scratch or distroless image.
Step 1: the first PDF in one file
Create an account and API key at portal.api2pdf.com and export it as API2PDF_API_KEY. There is no Go SDK to install; the API is JSON over HTTPS, so the standard library is enough:
// cmd/hello/main.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
body, _ := json.Marshal(map[string]any{
"html": "<h1>Hello from Go</h1><p>Rendered by Headless Chrome.</p>",
"fileName": "hello.pdf",
"inline": false,
})
req, _ := http.NewRequest("POST", "https://v2.api2pdf.com/chrome/pdf/html?outputBinary=true", bytes.NewReader(body))
req.Header.Set("Authorization", os.Getenv("API2PDF_API_KEY")) // the raw key, no "Bearer"
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
pdf, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
log.Fatalf("api2pdf: HTTP %d: %s", resp.StatusCode, pdf)
}
if err := os.WriteFile("hello.pdf", pdf, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("wrote hello.pdf (%d bytes)\n", len(pdf))
}
export API2PDF_API_KEY=your-key
go run ./cmd/hello
That is the whole integration. A wrong key shows up as api2pdf: HTTP 401: {"ResponseId":"...",...,"Error":"Invalid API key","Success":false,"FileUrl":null}: failures come back as JSON even when you ask for binary output. The rest of this post turns those 30 lines into something you can run in production. All code below was compiled and tested with Go 1.27. It relies on Go 1.22 features (method-and-wildcard ServeMux patterns, per-iteration loop variables and math/rand/v2), current releases of golang.org/x/sync require Go 1.26, and the only third-party modules are golang.org/x/sync and, for the S3 section, the AWS SDK for Go v2.
Step 2: request and response types
The /chrome/pdf/html body takes html plus the optional fileName, inline, options (the Headless Chrome options) and, for your own storage, useCustomStorage and storage. Every JSON response carries Success, Error, FileUrl, MbOut, Seconds, Cost and ResponseId. With omitempty on every option, anything you leave at its zero value falls back to the API default (A4, 0.4 inch margins, backgrounds printed):
// api2pdf/types.go
package api2pdf
// ChromeOptions are the Headless Chrome PDF options. Zero values are omitted,
// so the API defaults apply (A4, .4in margins, printBackground on).
type ChromeOptions struct {
Landscape bool `json:"landscape,omitempty"`
Scale float64 `json:"scale,omitempty"`
Width string `json:"width,omitempty"` // e.g. "8.5in"
Height string `json:"height,omitempty"` // e.g. "11in"
MarginTop string `json:"marginTop,omitempty"`
MarginBottom string `json:"marginBottom,omitempty"`
MarginLeft string `json:"marginLeft,omitempty"`
MarginRight string `json:"marginRight,omitempty"`
PreferCSSPageSize bool `json:"preferCSSPageSize,omitempty"`
DisplayHeaderFooter bool `json:"displayHeaderFooter,omitempty"`
HeaderTemplate string `json:"headerTemplate,omitempty"`
FooterTemplate string `json:"footerTemplate,omitempty"`
Outline bool `json:"outline,omitempty"`
Delay int `json:"delay,omitempty"` // milliseconds
PuppeteerWaitForMethod string `json:"puppeteerWaitForMethod,omitempty"`
PuppeteerWaitForValue string `json:"puppeteerWaitForValue,omitempty"`
}
// Storage tells Api2Pdf to upload the result to your own bucket
// (an S3 presigned PUT URL, a GCS signed URL or an Azure SAS URL).
type Storage struct {
Method string `json:"method"`
URL string `json:"url"`
ExtraHTTPHeaders map[string]string `json:"extraHTTPHeaders,omitempty"`
}
// HTMLRequest is the body of POST /chrome/pdf/html.
type HTMLRequest struct {
HTML string `json:"html"`
FileName string `json:"fileName,omitempty"`
Inline bool `json:"inline"`
Options *ChromeOptions `json:"options,omitempty"`
UseCustomStorage bool `json:"useCustomStorage,omitempty"`
Storage *Storage `json:"storage,omitempty"`
}
// MergeRequest is the body of POST /pdfsharp/merge. URLs are merged in order.
type MergeRequest struct {
URLs []string `json:"urls"`
FileName string `json:"fileName,omitempty"`
Inline bool `json:"inline"`
UseCustomStorage bool `json:"useCustomStorage,omitempty"`
Storage *Storage `json:"storage,omitempty"`
}
// PasswordRequest is the body of POST /pdfsharp/password.
type PasswordRequest struct {
URL string `json:"url"`
UserPassword string `json:"userpassword"`
OwnerPassword string `json:"ownerpassword,omitempty"`
FileName string `json:"fileName,omitempty"`
Inline bool `json:"inline"`
}
// Result is the JSON response of every conversion endpoint.
type Result struct {
Success bool `json:"Success"`
Error string `json:"Error"`
FileURL string `json:"FileUrl"` // hosted by Api2Pdf for 24 hours
MbOut float64 `json:"MbOut"`
Seconds float64 `json:"Seconds"`
Cost float64 `json:"Cost"`
ResponseID string `json:"ResponseId"`
}
Step 3: one error type that knows what to retry
A single error type carries the HTTP status, the API's Error message, the ResponseId for support, and whether retrying can help. Network errors, 429 and 5xx are temporary; a bad key, a missing html field or an unreachable source URL are not:
// api2pdf/error.go
package api2pdf
import (
"errors"
"fmt"
"net/http"
)
// Error is returned for every failed Api2Pdf call.
type Error struct {
Op string // e.g. "POST /chrome/pdf/html"
StatusCode int // 0 for network errors
Message string // the API's Error field, or a short body excerpt
ResponseID string // quote this to support
Err error // underlying network error, if any
}
func (e *Error) Error() string {
if e.Err != nil {
return fmt.Sprintf("api2pdf: %s: %v", e.Op, e.Err)
}
return fmt.Sprintf("api2pdf: %s: HTTP %d: %s", e.Op, e.StatusCode, e.Message)
}
func (e *Error) Unwrap() error { return e.Err }
// Temporary reports whether retrying the same request may succeed:
// network errors, 429 and 5xx. A bad key or invalid input is permanent.
func (e *Error) Temporary() bool {
if e.Err != nil {
return true
}
return e.StatusCode == http.StatusTooManyRequests || e.StatusCode >= 500
}
// IsTemporary is a helper for callers that only have an error.
func IsTemporary(err error) bool {
var apiErr *Error
return errors.As(err, &apiErr) && apiErr.Temporary()
}
Step 4: a small client with context-aware retries
The client is under 200 lines of standard library. Three details matter in production:
- The context bounds everything. Every request uses
http.NewRequestWithContext, and the backoff waits in aselectonctx.Done(). When a user closes the tab or a job is cancelled, the in-flight call and any pending retries stop immediately. - Retries with exponential backoff and jitter (0.5 s, 1 s, 2 s, plus up to 0.5 s of jitter) for temporary failures only. The request body is marshalled once and replayed from a fresh
bytes.Readeron each attempt. - Binary responses are streamed, not buffered.
HTMLToPDFStreampeeks at the first four bytes through abufio.Readerto confirm the body starts with%PDF, then hands the stream back so a 40 MB report never sits in memory.
// api2pdf/client.go
// Package api2pdf is a small, dependency-free client for the Api2Pdf REST API.
package api2pdf
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"math/rand/v2"
"net/http"
"time"
)
const (
DefaultBaseURL = "https://v2.api2pdf.com"
XLBaseURL = "https://v2-xl.api2pdf.com" // 4 CPU, 8 GB, 5 minute limit
)
type Client struct {
BaseURL string
APIKey string
HTTP *http.Client
MaxAttempts int // total tries per call, including the first
RetryDelay time.Duration // base delay, doubled on each retry
}
// New returns a client with production defaults. Standard requests finish
// within 90 seconds on the Api2Pdf side, so 120 seconds covers upload and
// download time as well.
func New(apiKey string) *Client {
return &Client{
BaseURL: DefaultBaseURL,
APIKey: apiKey,
HTTP: &http.Client{Timeout: 120 * time.Second},
MaxAttempts: 4,
RetryDelay: 500 * time.Millisecond,
}
}
// HTMLToPDF renders HTML with Headless Chrome and returns the hosted file.
// Use this form when you chain endpoints (merge, password, watermark).
func (c *Client) HTMLToPDF(ctx context.Context, r HTMLRequest) (*Result, error) {
return c.postJSON(ctx, "/chrome/pdf/html", r)
}
// HTMLToPDFStream renders HTML and returns the PDF bytes as a stream
// (outputBinary=true). The caller must close it.
func (c *Client) HTMLToPDFStream(ctx context.Context, r HTMLRequest) (io.ReadCloser, error) {
return c.postBinary(ctx, "/chrome/pdf/html", r)
}
// HTMLToPDFBytes is HTMLToPDFStream read into memory, for attachments.
func (c *Client) HTMLToPDFBytes(ctx context.Context, r HTMLRequest) ([]byte, error) {
rc, err := c.HTMLToPDFStream(ctx, r)
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
// Merge combines PDFs (public or presigned URLs) in the given order.
func (c *Client) Merge(ctx context.Context, r MergeRequest) (*Result, error) {
return c.postJSON(ctx, "/pdfsharp/merge", r)
}
// Password adds an open (user) password and an optional owner password.
func (c *Client) Password(ctx context.Context, r PasswordRequest) (*Result, error) {
return c.postJSON(ctx, "/pdfsharp/password", r)
}
// Delete removes a hosted file before its 24 hour expiry.
func (c *Client) Delete(ctx context.Context, responseID string) error {
resp, err := c.send(ctx, http.MethodDelete, "/file/"+responseID, nil)
if err != nil {
return err
}
resp.Body.Close()
return nil
}
func (c *Client) postJSON(ctx context.Context, path string, body any) (*Result, error) {
payload, err := json.Marshal(body)
if err != nil {
return nil, err
}
resp, err := c.send(ctx, http.MethodPost, path, payload)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res Result
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, &Error{Op: "POST " + path, StatusCode: resp.StatusCode, Err: err}
}
if !res.Success {
return nil, &Error{Op: "POST " + path, StatusCode: resp.StatusCode, Message: res.Error, ResponseID: res.ResponseID}
}
return &res, nil
}
func (c *Client) postBinary(ctx context.Context, path string, body any) (io.ReadCloser, error) {
payload, err := json.Marshal(body)
if err != nil {
return nil, err
}
resp, err := c.send(ctx, http.MethodPost, path+"?outputBinary=true", payload)
if err != nil {
return nil, err
}
// Check the magic bytes without buffering the whole document.
br := bufio.NewReader(resp.Body)
if magic, _ := br.Peek(4); string(magic) != "%PDF" {
excerpt, _ := io.ReadAll(io.LimitReader(br, 500))
resp.Body.Close()
return nil, &Error{Op: "POST " + path, StatusCode: resp.StatusCode, Message: "not a PDF: " + string(magic) + string(excerpt)}
}
return struct {
io.Reader
io.Closer
}{br, resp.Body}, nil
}
// send performs the request with retries and returns a 2xx response.
// Network errors, 429 and 5xx are retried with exponential backoff and
// jitter; the context bounds the whole thing, including the waits.
func (c *Client) send(ctx context.Context, method, path string, payload []byte) (*http.Response, error) {
op := method + " " + path
attempts := max(c.MaxAttempts, 1)
for attempt := 0; ; attempt++ {
resp, err := c.once(ctx, method, path, payload)
if err == nil && resp.StatusCode < 300 {
return resp, nil
}
var apiErr *Error
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
apiErr = &Error{Op: op, Err: err}
} else {
apiErr = errorFromResponse(op, resp)
}
if !apiErr.Temporary() || attempt+1 >= attempts {
return nil, apiErr
}
wait := c.RetryDelay<<attempt + rand.N(c.RetryDelay+1)
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
}
}
func (c *Client) once(ctx context.Context, method, path string, payload []byte) (*http.Response, error) {
var body io.Reader
if payload != nil {
body = bytes.NewReader(payload)
}
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.APIKey) // the raw key, no "Bearer" prefix
if payload != nil {
req.Header.Set("Content-Type", "application/json")
}
return c.HTTP.Do(req)
}
// errorFromResponse turns a non-2xx response into an *Error. Failures come
// back as JSON ({"Success":false,"Error":"..."}) even with outputBinary=true.
func errorFromResponse(op string, resp *http.Response) *Error {
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
e := &Error{Op: op, StatusCode: resp.StatusCode, Message: string(raw)}
var res Result
if json.Unmarshal(raw, &res) == nil && res.Error != "" {
e.Message, e.ResponseID = res.Error, res.ResponseID
}
if e.Message == "" {
e.Message = http.StatusText(resp.StatusCode)
}
return e
}
The http.Client timeout of 120 seconds is deliberate: standard Api2Pdf requests get up to 90 seconds of processing, and the extra headroom covers upload and download time. For very large documents, point a second client at XLBaseURL and raise the timeout (see the production notes below).
Step 5: the invoice template
html/template is a good fit for PDFs because it escapes every value by context. A customer named <script> renders as text, not markup. Embed the templates with embed.FS so the binary stays self-contained, and register a few helpers for money and dates:
// invoice/invoice.go
// Package invoice renders invoices to HTML with html/template.
package invoice
import (
"bytes"
"embed"
"fmt"
"html/template"
"time"
)
type Line struct {
Description string
Quantity int
UnitCents int64
}
type Invoice struct {
Number string
Customer string
Email string
Issued time.Time
Due time.Time
Lines []Line
}
func (i Invoice) TotalCents() int64 {
var t int64
for _, l := range i.Lines {
t += int64(l.Quantity) * l.UnitCents
}
return t
}
//go:embed templates/*.html
var files embed.FS
var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
"money": func(cents int64) string { return fmt.Sprintf("$%d.%02d", cents/100, cents%100) },
"mul": func(q int, c int64) int64 { return int64(q) * c },
"date": func(t time.Time) string { return t.Format("January 2, 2006") },
}).ParseFS(files, "templates/*.html"))
// HTML renders the invoice template. html/template escapes every value,
// so customer-supplied text cannot inject markup into the PDF.
func HTML(inv Invoice) (string, error) {
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "invoice.html", inv); err != nil {
return "", err
}
return buf.String(), nil
}
<!-- invoice/templates/invoice.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Invoice {{.Number}}</title>
<style>
body { font-family: -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: #1f2937; font-size: 12px; }
header { display: flex; justify-content: space-between; align-items: flex-start; }
h1 { font-size: 24px; margin: 0 0 4px; }
table { width: 100%; border-collapse: collapse; margin-top: 24px; }
thead { display: table-header-group; }
th, td { padding: 8px; border-bottom: 1px solid #e5e7eb; text-align: left; }
td.num, th.num { text-align: right; }
tr { break-inside: avoid; }
.total td { font-weight: 700; border-bottom: none; }
</style>
</head>
<body>
<header>
<div>
<h1>Invoice {{.Number}}</h1>
<div>Issued {{date .Issued}} · Due {{date .Due}}</div>
</div>
<div style="text-align:right">
<strong>{{.Customer}}</strong><br>{{.Email}}
</div>
</header>
<table>
<thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Unit</th><th class="num">Amount</th></tr></thead>
<tbody>
{{range .Lines}}
<tr><td>{{.Description}}</td><td class="num">{{.Quantity}}</td><td class="num">{{money .UnitCents}}</td><td class="num">{{money (mul .Quantity .UnitCents)}}</td></tr>
{{end}}
<tr class="total"><td colspan="3">Total</td><td class="num">{{money .TotalCents}}</td></tr>
</tbody>
</table>
</body>
</html>
Headless Chrome renders flexbox, grid and web fonts the way your browser does. A few print rules help long documents: display: table-header-group repeats the table header on every page, and break-inside: avoid keeps a row from splitting across pages.
The page setup lives in one function so every caller (download, batch, S3 export) produces the same document: US Letter, half-inch margins and a page-number footer. Chrome renders footerTemplate in its own context, so it needs inline styles and an explicit font-size, and fills pageNumber and totalPages for you:
// invoice/pdf.go
package invoice
import (
"example.com/billing/api2pdf"
)
// footer is rendered by Chrome in its own context: inline styles only,
// and an explicit font-size or the text comes out tiny.
const footer = `<div style="font-size:9px;width:100%;text-align:center;color:#6b7280">` +
`Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`
// PDFRequest builds the Api2Pdf request for one invoice: US Letter,
// half-inch margins and a page-number footer.
func PDFRequest(inv Invoice) (api2pdf.HTMLRequest, error) {
html, err := HTML(inv)
if err != nil {
return api2pdf.HTMLRequest{}, err
}
return api2pdf.HTMLRequest{
HTML: html,
FileName: inv.Number + ".pdf",
Options: &api2pdf.ChromeOptions{
Width: "8.5in", Height: "11in",
MarginTop: "0.5in", MarginBottom: "0.75in", MarginLeft: "0.5in", MarginRight: "0.5in",
DisplayHeaderFooter: true,
HeaderTemplate: "<span></span>",
FooterTemplate: footer,
},
}, nil
}
Step 6: stream the PDF from an HTTP handler
The handler loads the invoice, renders the template, calls Api2Pdf with outputBinary=true and copies the stream straight to the response. It derives its context from r.Context(), so a client that disconnects cancels the Api2Pdf call too. Failures are logged with the ResponseId and returned to the user as a plain 502, without internal details:
// invoice/handler.go
package invoice
import (
"context"
"errors"
"io"
"log/slog"
"mime"
"net/http"
"time"
"example.com/billing/api2pdf"
)
type Handler struct {
PDF *api2pdf.Client
Store Store
Log *slog.Logger
}
// DownloadPDF serves GET /invoices/{number}/pdf.
func (h *Handler) DownloadPDF(w http.ResponseWriter, r *http.Request) {
number := r.PathValue("number")
inv, err := h.Store.Get(r.Context(), number)
if errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "could not load invoice", http.StatusInternalServerError)
return
}
// Authorize the current user for this invoice here.
req, err := PDFRequest(inv)
if err != nil {
h.Log.Error("render invoice template", "invoice", number, "err", err)
http.Error(w, "could not render invoice", http.StatusInternalServerError)
return
}
// r.Context() is cancelled if the browser goes away, which also stops retries.
ctx, cancel := context.WithTimeout(r.Context(), 100*time.Second)
defer cancel()
pdf, err := h.PDF.HTMLToPDFStream(ctx, req)
if err != nil {
var apiErr *api2pdf.Error
if errors.As(err, &apiErr) {
h.Log.Error("api2pdf", "invoice", number, "status", apiErr.StatusCode, "responseId", apiErr.ResponseID, "err", apiErr.Message)
} else {
h.Log.Error("api2pdf", "invoice", number, "err", err)
}
http.Error(w, "PDF generation failed, please try again", http.StatusBadGateway)
return
}
defer pdf.Close()
disposition := "inline"
if r.URL.Query().Get("download") == "1" {
disposition = "attachment"
}
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": req.FileName}))
w.Header().Set("Cache-Control", "private, no-store")
if _, err := io.Copy(w, pdf); err != nil {
h.Log.Warn("stream pdf", "invoice", number, "err", err)
}
}
// invoice/store.go
package invoice
import (
"context"
"errors"
"time"
)
var ErrNotFound = errors.New("invoice not found")
// Store is whatever you load invoices from: a database, an API, a cache.
type Store interface {
Get(ctx context.Context, number string) (Invoice, error)
}
// MemoryStore is a tiny in-memory Store for the examples and tests.
type MemoryStore map[string]Invoice
func (m MemoryStore) Get(_ context.Context, number string) (Invoice, error) {
inv, ok := m[number]
if !ok {
return Invoice{}, ErrNotFound
}
return inv, nil
}
// Sample returns a store with one invoice, INV-1001.
func Sample() MemoryStore {
issued := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC)
return MemoryStore{"INV-1001": {
Number: "INV-1001", Customer: "Acme Corp", Email: "[email protected]",
Issued: issued, Due: issued.AddDate(0, 0, 30),
Lines: []Line{
{Description: "Pro plan, November 2026", Quantity: 1, UnitCents: 4900},
{Description: "Extra seats", Quantity: 3, UnitCents: 900},
},
}}
}
Wire it up with the Go 1.22 routing patterns. Set WriteTimeout longer than the Api2Pdf call, or the server will cut off slow renders:
// cmd/server/main.go
package main
import (
"log/slog"
"net/http"
"os"
"time"
"example.com/billing/api2pdf"
"example.com/billing/invoice"
)
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
key := os.Getenv("API2PDF_API_KEY")
if key == "" {
log.Error("API2PDF_API_KEY is not set")
os.Exit(1)
}
h := &invoice.Handler{PDF: api2pdf.New(key), Store: invoice.Sample(), Log: log}
mux := http.NewServeMux()
mux.HandleFunc("GET /invoices/{number}/pdf", h.DownloadPDF)
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 150 * time.Second, // longer than the Api2Pdf call
}
log.Info("listening", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil {
log.Error("server", "err", err)
os.Exit(1)
}
}
go run ./cmd/server
curl -o INV-1001.pdf "http://localhost:8080/invoices/INV-1001/pdf?download=1"
Step 7: render a batch concurrently, merge and password-protect it
Month-end statements are many small documents that should end up as one file. errgroup with SetLimit renders them in parallel with bounded concurrency and cancels the rest on the first permanent error. Each goroutine writes to its own slice index, so the merge order matches the input order with no mutex. Api2Pdf has no rate limits; the limit is there to keep your own process and network comfortable. The merged file is then passed to /pdfsharp/password, and every intermediate file is deleted with DELETE /file/{responseId} instead of waiting 24 hours:
// invoice/packet.go
package invoice
import (
"context"
"fmt"
"example.com/billing/api2pdf"
"golang.org/x/sync/errgroup"
)
// StatementPacket renders every invoice in parallel (at most 4 in flight),
// merges them in order and protects the result with a password. It returns
// the final file, which Api2Pdf hosts for 24 hours.
func StatementPacket(ctx context.Context, c *api2pdf.Client, invoices []Invoice, name, password string) (*api2pdf.Result, error) {
parts := make([]*api2pdf.Result, len(invoices))
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(4)
for i, inv := range invoices {
g.Go(func() error {
req, err := PDFRequest(inv)
if err != nil {
return err
}
res, err := c.HTMLToPDF(gctx, req)
if err != nil {
return fmt.Errorf("invoice %s: %w", inv.Number, err)
}
parts[i] = res // each goroutine writes its own index: no mutex needed
return nil
})
}
err := g.Wait()
// Clean up the intermediate files whether or not the batch succeeded.
defer func() {
for _, p := range parts {
if p != nil {
_ = c.Delete(context.WithoutCancel(ctx), p.ResponseID)
}
}
}()
if err != nil {
return nil, err
}
urls := make([]string, len(parts))
for i, p := range parts {
urls[i] = p.FileURL
}
merged, err := c.Merge(ctx, api2pdf.MergeRequest{URLs: urls, FileName: name + "-unlocked.pdf"})
if err != nil {
return nil, err
}
defer c.Delete(context.WithoutCancel(ctx), merged.ResponseID)
return c.Password(ctx, api2pdf.PasswordRequest{
URL: merged.FileURL, UserPassword: password, FileName: name + ".pdf",
})
}
The returned FileURL is valid for 24 hours: email the link, redirect to it, or copy it to your own storage. For DRAFT or CONFIDENTIAL stamps on the same pipeline, add one call to POST /pdfsharp/watermark (body: url, text, fontSize, color, opacity, rotation) as shown in the Laravel guide.
Step 8: write PDFs straight into your S3 bucket with useCustomStorage
When the PDF belongs in your own storage (an archive, a customer portal, a data lake), downloading it from Api2Pdf only to upload it again wastes bandwidth and memory. Instead, presign a PUT for the exact object key and pass it in the request. Api2Pdf renders the PDF and uploads it to that URL itself. Nothing else in your AWS account is exposed: the URL can write one object, with one method, for a few minutes.
The AWS SDK for Go v2 returns the headers the upload must send along with the presigned URL (SignedHeader). Because the input sets ContentType, content-type is a signed header, so it has to go into storage.extraHTTPHeaders with the exact same value. That is also what makes S3 store the object as application/pdf instead of binary/octet-stream:
// export/s3.go
// Package export writes PDFs straight into your own S3 bucket.
package export
import (
"context"
"fmt"
"net/http"
"time"
"example.com/billing/api2pdf"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
type S3Exporter struct {
PDF *api2pdf.Client
S3 *s3.Client
Bucket string
}
// RenderToS3 renders HTML and has Api2Pdf PUT the PDF directly into
// s3://Bucket/key through a presigned URL. The PDF never passes through
// your server, and the Api2Pdf-hosted copy is not needed.
func (e *S3Exporter) RenderToS3(ctx context.Context, req api2pdf.HTMLRequest, key string) (int64, error) {
put, err := s3.NewPresignClient(e.S3).PresignPutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(e.Bucket),
Key: aws.String(key),
ContentType: aws.String("application/pdf"),
}, s3.WithPresignExpires(15*time.Minute)) // must outlive the render
if err != nil {
return 0, fmt.Errorf("presign: %w", err)
}
req.UseCustomStorage = true
req.Storage = &api2pdf.Storage{
Method: http.MethodPut,
URL: put.URL,
ExtraHTTPHeaders: signedHeaders(put.SignedHeader),
}
if _, err := e.PDF.HTMLToPDF(ctx, req); err != nil {
return 0, err
}
head, err := e.S3.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(e.Bucket), Key: aws.String(key)})
if err != nil {
return 0, fmt.Errorf("verify upload: %w", err)
}
return aws.ToInt64(head.ContentLength), nil
}
// signedHeaders returns the headers the upload must send for the signature
// to match (Content-Type here). Host is set by the HTTP client itself.
func signedHeaders(h http.Header) map[string]string {
out := map[string]string{}
for k, v := range h {
if http.CanonicalHeaderKey(k) != "Host" && len(v) > 0 {
out[http.CanonicalHeaderKey(k)] = v[0]
}
}
return out
}
go get github.com/aws/aws-sdk-go-v2/config github.com/aws/aws-sdk-go-v2/service/s3
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("us-east-1"))
if err != nil {
return err
}
exp := &export.S3Exporter{PDF: api2pdf.New(os.Getenv("API2PDF_API_KEY")), S3: s3.NewFromConfig(cfg), Bucket: "acme-invoices"}
req, err := invoice.PDFRequest(inv)
if err != nil {
return err
}
size, err := exp.RenderToS3(ctx, req, "invoices/2026/11/"+inv.Number+".pdf")
Three things to get right:
- Send every signed header. A missing or different
Content-Typegets a403 SignatureDoesNotMatchfrom S3 and the upload fails. BuildingextraHTTPHeadersfromSignedHeaderkeeps the two in sync if you later sign more headers, such asx-amz-server-side-encryption. - Make the expiry outlive the render. The URL has to be valid when Api2Pdf finishes, not just when you send the request. Presign right before the call and allow a few minutes (15 above).
- Verify, then trust. The
HeadObjectcheck confirms the object exists and returns its size, which is the number worth recording in your database.
useCustomStorage and storage work the same way on the other conversion endpoints, including merge, LibreOffice and /zip (see batch PDF generation: zip PDFs and upload to S3). Other clouds follow the same pattern: a Google Cloud Storage V4 signed URL for PUT (with the signed Content-Type in extraHTTPHeaders), or an Azure Blob SAS URL with x-ms-blob-type: BlockBlob in extraHTTPHeaders, which Azure requires on every Put Blob request.
Step 9: test without the network
Because the base URL is a field, httptest.NewServer can stand in for Api2Pdf in every test. These tests check the raw Authorization header and JSON body, that a 503 is retried and a 400 is not, that Success: false is an error, and that a cancelled context stops the retry loop:
// api2pdf/client_test.go
package api2pdf
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func testClient(url string) *Client {
c := New("test-key")
c.BaseURL = url
c.RetryDelay = time.Millisecond
return c
}
func TestHTMLToPDFSendsRawKeyAndJSON(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/chrome/pdf/html" || r.Method != http.MethodPost {
t.Errorf("got %s %s", r.Method, r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "test-key" {
t.Errorf("Authorization = %q, want the raw key", got)
}
var body map[string]any
json.NewDecoder(r.Body).Decode(&body)
if body["html"] != "<h1>Hi</h1>" || body["inline"] != false || body["fileName"] != "a.pdf" {
t.Errorf("unexpected body %v", body)
}
if _, ok := body["useCustomStorage"]; ok {
t.Errorf("useCustomStorage should be omitted when false")
}
io.WriteString(w, `{"Success":true,"FileUrl":"https://storage.example/a.pdf","ResponseId":"r1","Cost":0.0001}`)
}))
defer srv.Close()
res, err := testClient(srv.URL).HTMLToPDF(context.Background(), HTMLRequest{HTML: "<h1>Hi</h1>", FileName: "a.pdf"})
if err != nil {
t.Fatal(err)
}
if res.FileURL != "https://storage.example/a.pdf" || res.ResponseID != "r1" {
t.Errorf("unexpected result %+v", res)
}
}
func TestRetriesTransientFailures(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) < 3 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
io.WriteString(w, "%PDF-1.7 fake")
}))
defer srv.Close()
pdf, err := testClient(srv.URL).HTMLToPDFBytes(context.Background(), HTMLRequest{HTML: "x"})
if err != nil {
t.Fatal(err)
}
if string(pdf) != "%PDF-1.7 fake" || calls.Load() != 3 {
t.Errorf("pdf=%q calls=%d", pdf, calls.Load())
}
}
func TestDoesNotRetryBadRequest(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, `{"Success":false,"Error":"html is required","ResponseId":"r2"}`)
}))
defer srv.Close()
_, err := testClient(srv.URL).HTMLToPDFStream(context.Background(), HTMLRequest{})
var apiErr *Error
if !errors.As(err, &apiErr) || apiErr.StatusCode != 400 || apiErr.Message != "html is required" || apiErr.ResponseID != "r2" {
t.Fatalf("unexpected error %#v", err)
}
if apiErr.Temporary() || calls.Load() != 1 {
t.Errorf("400 must not be retried, calls=%d", calls.Load())
}
}
func TestSuccessFalseIsAnError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"Success":false,"Error":"could not reach url","ResponseId":"r3"}`)
}))
defer srv.Close()
_, err := testClient(srv.URL).Merge(context.Background(), MergeRequest{URLs: []string{"https://x"}})
if err == nil || IsTemporary(err) {
t.Fatalf("want a permanent error, got %v", err)
}
}
func TestContextStopsRetries(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
}))
defer srv.Close()
c := testClient(srv.URL)
c.RetryDelay = time.Second
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
start := time.Now()
_, err := c.HTMLToPDF(ctx, HTMLRequest{HTML: "x"})
if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 500*time.Millisecond {
t.Fatalf("err=%v after %s", err, time.Since(start))
}
}
The handler test runs the real template, the real client and a fake Api2Pdf, and checks the headers a browser sees:
// invoice/handler_test.go
package invoice
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"example.com/billing/api2pdf"
)
func TestDownloadPDF(t *testing.T) {
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("outputBinary") != "true" {
t.Errorf("want outputBinary=true, got %q", r.URL.RawQuery)
}
var req api2pdf.HTMLRequest
json.NewDecoder(r.Body).Decode(&req)
if !strings.Contains(req.HTML, "Invoice INV-1001") || !strings.Contains(req.HTML, "$76.00") {
t.Errorf("template not rendered: %.200s", req.HTML)
}
if req.Options == nil || !req.Options.DisplayHeaderFooter || req.Options.Width != "8.5in" {
t.Errorf("options: %+v", req.Options)
}
io.WriteString(w, "%PDF-1.7 fake invoice")
}))
defer fake.Close()
client := api2pdf.New("k")
client.BaseURL = fake.URL
h := &Handler{PDF: client, Store: Sample(), Log: slog.New(slog.DiscardHandler)}
mux := http.NewServeMux()
mux.HandleFunc("GET /invoices/{number}/pdf", h.DownloadPDF)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/invoices/INV-1001/pdf?download=1", nil))
if rec.Code != 200 || rec.Header().Get("Content-Type") != "application/pdf" {
t.Fatalf("status %d, headers %v", rec.Code, rec.Header())
}
if got := rec.Header().Get("Content-Disposition"); got != `attachment; filename=INV-1001.pdf` {
t.Errorf("Content-Disposition = %q", got)
}
if rec.Body.String() != "%PDF-1.7 fake invoice" {
t.Errorf("body %q", rec.Body.String())
}
rec = httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/invoices/NOPE/pdf", nil))
if rec.Code != 404 {
t.Errorf("unknown invoice: status %d", rec.Code)
}
}
func TestTemplateEscapesInput(t *testing.T) {
inv := Sample()["INV-1001"]
inv.Customer = `<script>alert(1)</script>`
html, err := HTML(inv)
if err != nil {
t.Fatal(err)
}
if strings.Contains(html, "<script>alert") {
t.Error("customer name was not escaped")
}
}
The S3 exporter can be tested end to end without AWS: point the SDK at a second httptest server with BaseEndpoint and UsePathStyle, and have the fake Api2Pdf do what the real one does, a PUT to storage.url with storage.extraHTTPHeaders:
// export/s3_test.go
package export
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strconv"
"sync"
"testing"
"example.com/billing/api2pdf"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// A fake S3 bucket and a fake Api2Pdf that, like the real one, uploads
// the result to storage.url with storage.method and storage.extraHTTPHeaders.
func TestRenderToS3(t *testing.T) {
var mu sync.Mutex
objects := map[string][]byte{}
contentTypes := map[string]string{}
s3srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
switch r.Method {
case http.MethodPut:
if r.URL.Query().Get("X-Amz-Signature") == "" {
t.Errorf("PUT is not presigned: %s", r.URL)
}
if !bytes.Contains([]byte(r.URL.Query().Get("X-Amz-SignedHeaders")), []byte("content-type")) {
t.Errorf("content-type not signed: %s", r.URL.RawQuery)
}
b, _ := io.ReadAll(r.Body)
objects[r.URL.Path] = b
contentTypes[r.URL.Path] = r.Header.Get("Content-Type")
case http.MethodHead:
b, ok := objects[r.URL.Path]
if !ok {
w.WriteHeader(404)
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
}
}))
defer s3srv.Close()
a2p := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req api2pdf.HTMLRequest
json.NewDecoder(r.Body).Decode(&req)
if !req.UseCustomStorage || req.Storage == nil || req.Storage.Method != "PUT" {
t.Fatalf("storage not set: %+v", req)
}
put, _ := http.NewRequest(req.Storage.Method, req.Storage.URL, bytes.NewReader([]byte("%PDF-1.7 fake")))
for k, v := range req.Storage.ExtraHTTPHeaders {
put.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(put)
if err != nil || resp.StatusCode != 200 {
t.Fatalf("upload failed: %v", err)
}
io.WriteString(w, `{"Success":true,"ResponseId":"r1"}`)
}))
defer a2p.Close()
s3c := s3.New(s3.Options{
Region: "us-east-1",
BaseEndpoint: aws.String(s3srv.URL),
UsePathStyle: true,
Credentials: credentials.NewStaticCredentialsProvider("AKID", "SECRET", ""),
})
pdf := api2pdf.New("k")
pdf.BaseURL = a2p.URL
e := &S3Exporter{PDF: pdf, S3: s3c, Bucket: "exports"}
n, err := e.RenderToS3(context.Background(), api2pdf.HTMLRequest{HTML: "<h1>x</h1>"}, "invoices/2026/11/INV-1001.pdf")
if err != nil {
t.Fatal(err)
}
if n != int64(len("%PDF-1.7 fake")) {
t.Errorf("size %d", n)
}
if ct := contentTypes["/exports/invoices/2026/11/INV-1001.pdf"]; ct != "application/pdf" {
t.Errorf("content-type %q (all: %v)", ct, contentTypes)
}
}
go test -race ./...
ok example.com/billing/api2pdf 1.081s
ok example.com/billing/export 1.023s
ok example.com/billing/invoice 1.029s
Production notes
- Keep the key server-side. Never call Api2Pdf from browser JavaScript; the key in the
Authorizationheader would be visible to every visitor. Go through a handler that authorizes the user first. - Reuse one client.
*api2pdf.Clientand itshttp.Clientare safe for concurrent use and pool connections. Create one at startup and share it, rather than one per request. - Pick the right path for each document. Stream small documents from the handler; move big, bulk or chained work to a background worker or queue, and use
useCustomStoragewhen the result belongs in your bucket anyway. - Use V2 XL for large documents. Standard requests get 2 GB of memory and 90 seconds. Long reports with hundreds of pages or heavy charts can use a second client with
BaseURL: api2pdf.XLBaseURL(4 CPU, 8 GB, 5 minute limit, priced at 10x the standard rate) and anhttp.Clienttimeout of about 6 minutes. Use it only for those jobs. - Mind the 24 hour
FileUrl. Hosted files are deleted after 24 hours. Copy what you need to keep, delete sensitive files early withDelete, or skip the hosted copy entirely withuseCustomStorage. - Log the
ResponseId, not the HTML. The id appears in the request logs in the portal, and support can trace a request with it. Rendered documents usually contain personal data, so keep them out of your logs. - Cost is per use. Billing is based on compute seconds and bandwidth, and each JSON response reports
Seconds,MbOutandCost, so you can export per-feature cost metrics from the JSON calls. A one-page invoice usually costs a fraction of a cent.
Troubleshooting
- 401 Invalid API key. The header must be the key on its own. Remove any
Bearerprefix, trim trailing whitespace or newlines from the environment variable, and confirm the deployed environment setsAPI2PDF_API_KEY. not a PDFfromHTMLToPDFStream. A proxy or captive portal returned HTML instead of the API response. The error includes the first bytes of the body; check outbound proxy settings andHTTPS_PROXY.- Styles or images missing. The CSS or image is on a host Api2Pdf cannot reach, such as
localhostor a private network. Inline the CSS in the template and use public absolute URLs ordata:URIs for images. - Charts or JavaScript-rendered content is blank. The page was printed before the scripts finished. Set
Delay(milliseconds) or wait for a condition withPuppeteerWaitForMethodandPuppeteerWaitForValue, as described in the Headless Chrome options. Better still, render charts as SVG on the server. context deadline exceeded. Your context orhttp.Clienttimeout fired before the render finished. Check for slow external images or fonts first, then raise the timeout or send the job to V2 XL. Also check the server'sWriteTimeout.- Tiny header or footer text, or none at all. Set
DisplayHeaderFooter, give the template an explicitfont-size, and leave enough bottom margin for it to fit. SignatureDoesNotMatchon S3 uploads. A signed header was not sent, or was sent with a different value. BuildextraHTTPHeadersfrom the presign result'sSignedHeaderas shown above, and make sure the presigned URL has not expired.
Wrap-up
You now have a Go PDF pipeline with no native dependencies: html/template documents with safe escaping, a standard-library client with context-aware retries and a typed error, a handler that streams PDFs without buffering them, a concurrent batch that ends in one merged, password-protected file, direct-to-S3 delivery with useCustomStorage, and tests that never touch the network. The same client covers the rest of the API with one more method each: Markdown to PDF, screenshots, Office conversion through LibreOffice, and file to Markdown extraction. Create a free account to get an API key, or browse the full request reference in the interactive API docs.



