Generate PDFs in Node.js and Express with Api2Pdf: Streaming, Retries, Merge, Watermark and S3

Summary. Most Node.js PDF tutorials end with npm install puppeteer, and that is where the production problems start: a full Chrome download baked into every image, missing shared libraries in slim containers, zombie browser processes, memory spikes under load, and a browser you now have to patch. The alternatives (PDFKit, pdfmake, jsPDF) avoid the browser but make you draw every line by hand instead of reusing HTML and CSS. This guide keeps HTML and CSS as the template language and hands rendering to the Api2Pdf Headless Chrome API. You will make a first call with the official api2pdf npm package, then build a dependency-free client on the built-in fetch with per-attempt timeouts, retries and AbortSignal cancellation, stream invoices from an Express 5 route without buffering them, assemble a year-end statement that is merged, stamped DRAFT and password-protected by the PdfSharp endpoints and written straight into S3, delete every intermediate file, and test all of it with node:test against a fake server.

Using another stack? There are companion posts for ASP.NET Core, Go, 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 on your server, never in browser JavaScript. Your Express app turns data into an HTML 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 route can pipe to the browser. Without it you get JSON with a FileUrl that Api2Pdf hosts for 24 hours plus a ResponseId. Because the PdfSharp endpoints (/pdfsharp/merge, /pdfsharp/watermark, /pdfsharp/password, /pdfsharp/extract-pages) take URLs as input, that FileUrl chains straight into the next step, and DELETE /file/{responseId} removes each intermediate when you are done. If the result belongs in your bucket, add useCustomStorage and a presigned URL and Api2Pdf uploads it there. No Chromium in your image, no native modules, nothing to patch when Chrome ships a security fix.

Step 1: the first PDF with the official npm package

Create an account and API key at portal.api2pdf.com. The quickest way to see a PDF is the official api2pdf package (2.1.0, Node 18+, no dependencies), which wraps every endpoint:

mkdir billing-pdf && cd billing-pdf
npm init -y && npm pkg set type=module
npm install api2pdf
export API2PDF_API_KEY=your-key
// hello.js
import Api2Pdf from "api2pdf"

const client = new Api2Pdf(process.env.API2PDF_API_KEY)

try {
  const result = await client.chromeHtmlToPdf("<h1>Hello from Node.js</h1>", {
    filename: "hello.pdf",
  })
  console.log(result.FileUrl) // hosted for 24 hours
} catch (err) {
  // The SDK rejects with the API's JSON body when Success is false.
  console.error("Api2Pdf error:", err.Error ?? err)
  process.exitCode = 1
}

node hello.js prints a link to the PDF. The package is CommonJS, and the default import works from ES modules as shown. It resolves with the JSON result and rejects with the API's JSON body when Success is false; pass outputBinary: true in the options to get a Buffer instead. That is all many scripts and cron jobs need. A web app usually wants a little more control: timeouts per attempt, retries that respect Retry-After, cancellation when the visitor closes the tab, streaming instead of buffering, and one error type to log. The API is JSON over HTTPS, so the rest of this post builds that client in about 180 lines on the built-in fetch. All code below was run and tested with Node.js 24 and Express 5.3; it needs Node 22.9 or later (for --env-file-if-exists; the client itself needs 20.3+ for AbortSignal.any).

npm install express@5 @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
cp .env.example .env   # then fill in the values
{
  "name": "billing-pdf",
  "private": true,
  "type": "module",
  "engines": {
    "node": ">=22.9"
  },
  "scripts": {
    "start": "node --env-file-if-exists=.env src/server.js",
    "test": "node --test test/*.test.js"
  },
  "dependencies": {
    "@aws-sdk/client-s3": "^3.1178.0",
    "@aws-sdk/s3-request-presigner": "^3.1178.0",
    "api2pdf": "^2.1.0",
    "express": "^5.3.0"
  }
}
API2PDF_API_KEY=your-key
STATEMENTS_BUCKET=my-statements
STATEMENT_PASSWORD=change-me
STATEMENT_OWNER_PASSWORD=change-me-too
AWS_REGION=us-east-1

Step 2: a fetch-based client with timeouts, retries and one error type

Three details decide whether a PDF client survives production:

  • Timeouts per attempt, cancellation per call. Standard Api2Pdf requests get up to 90 seconds of processing, so each attempt gets 120 seconds via AbortSignal.timeout. The caller's own signal (a closed browser tab, a job budget) is combined with it through AbortSignal.any. When the caller aborts, the client stops immediately and never retries; when only the attempt timed out, it tries again.
  • Retries only where they help. Network errors, 408, 429 and 5xx are retried with exponential backoff and full jitter, honouring Retry-After. A 400 or 401 will fail the same way every time, so it is returned at once. Retrying a POST is safe here: a conversion changes nothing on your side, so the worst case is paying for one render twice, and with useCustomStorage a retry overwrites the same object key.
  • Errors are parsed from JSON. Every Api2Pdf response, success or failure, carries Success, Error, FileUrl, MbOut, Seconds, Cost and ResponseId. Failures come back as JSON even when you asked for outputBinary=true, and a 200 with Success: false is still a failure. Api2PdfError keeps the operation, HTTP status and ResponseId, which is what you log and quote to support.
// src/api2pdf.js: a small, dependency-free Api2Pdf client for Node.js 22+.
const DEFAULT_BASE_URL = "https://v2.api2pdf.com"
const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504])

export class Api2PdfError extends Error {
  constructor(message, { operation, status, responseId, retryable = false, cause } = {}) {
    super(message, { cause })
    this.name = "Api2PdfError"
    this.operation = operation
    this.status = status
    this.responseId = responseId
    this.retryable = retryable
  }
}

const sleep = (ms, signal) =>
  new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, ms)
    signal?.addEventListener("abort", () => {
      clearTimeout(timer)
      reject(signal.reason)
    }, { once: true })
  })

export class Api2PdfClient {
  #apiKey
  #baseUrl
  #fetch

  constructor({
    apiKey,
    baseUrl = DEFAULT_BASE_URL,
    attemptTimeoutMs = 120_000, // standard requests get up to 90 s of processing
    maxAttempts = 3,
    fetch = globalThis.fetch,
  } = {}) {
    if (!apiKey) throw new Error("Api2PdfClient: apiKey is required")
    this.#apiKey = apiKey
    this.#baseUrl = baseUrl.replace(/\/$/, "")
    this.#fetch = fetch
    this.attemptTimeoutMs = attemptTimeoutMs
    this.maxAttempts = maxAttempts
  }

  // ---- Headless Chrome ----

  /** Render HTML and return the JSON result ({ FileUrl, ResponseId, Cost, ... }). */
  htmlToPdf(html, opts = {}) {
    return this.#json("POST", "/chrome/pdf/html", { html, ...opts }, opts.signal)
  }

  /** Render a public URL to PDF and return the JSON result. */
  urlToPdf(url, opts = {}) {
    return this.#json("POST", "/chrome/pdf/url", { url, ...opts }, opts.signal)
  }

  /** Render HTML and return the PDF itself as a web ReadableStream. */
  async htmlToPdfStream(html, opts = {}) {
    const res = await this.#send("POST", "/chrome/pdf/html?outputBinary=true", { html, ...opts }, opts.signal)
    const type = res.headers.get("content-type") ?? ""
    if (!res.ok || type.includes("json")) {
      // Failures are JSON even when outputBinary=true was requested.
      throw await this.#errorFrom(res, "chrome/pdf/html")
    }
    return res.body
  }

  // ---- PdfSharp: operations on existing PDFs (input is a URL) ----

  merge(urls, opts = {}) {
    return this.#json("POST", "/pdfsharp/merge", { urls, ...opts }, opts.signal)
  }

  /** start and end are 0-based and inclusive; negative values count from the end. */
  extractPages(url, { start, end, ...opts } = {}) {
    return this.#json("POST", "/pdfsharp/extract-pages", { url, start, end, ...opts }, opts.signal)
  }

  watermark(url, { text = "DRAFT", fontSize, color, opacity, rotation, ...opts } = {}) {
    return this.#json("POST", "/pdfsharp/watermark",
      { url, text, fontSize, color, opacity, rotation, ...opts }, opts.signal)
  }

  password(url, { userPassword, ownerPassword, ...opts }) {
    return this.#json("POST", "/pdfsharp/password",
      { url, userpassword: userPassword, ownerpassword: ownerPassword, ...opts }, opts.signal)
  }

  // ---- Utilities ----

  /** Delete a hosted file now instead of waiting for the 24 hour expiry. */
  deleteFile(responseId, { signal } = {}) {
    return this.#json("DELETE", `/file/${encodeURIComponent(responseId)}`, undefined, signal)
  }

  /** Remaining credit on the account, as returned by GET /balance. */
  balance({ signal } = {}) {
    return this.#json("GET", "/balance", undefined, signal)
  }

  // ---- plumbing ----

  async #json(method, path, body, signal) {
    const operation = path.slice(1).split("?")[0]
    const res = await this.#send(method, path, body, signal)
    let data
    try {
      data = await res.json()
    } catch (cause) {
      throw new Api2PdfError(`${operation}: response was not JSON (HTTP ${res.status})`,
        { operation, status: res.status, retryable: res.status >= 500, cause })
    }
    if (!res.ok || data?.Success === false) {
      throw new Api2PdfError(`${operation}: ${data?.Error ?? `HTTP ${res.status}`}`,
        { operation, status: res.status, responseId: data?.ResponseId,
          retryable: RETRYABLE_STATUS.has(res.status) })
    }
    return data
  }

  // Sends one logical request with per-attempt timeouts and retries.
  // Returns the Response once it is a non-retryable answer (2xx or a 4xx you must fix).
  async #send(method, path, body, signal) {
    const payload = body === undefined ? undefined : JSON.stringify(stripSignal(body))
    for (let attempt = 1; ; attempt++) {
      const attemptSignal = signal
        ? AbortSignal.any([signal, AbortSignal.timeout(this.attemptTimeoutMs)])
        : AbortSignal.timeout(this.attemptTimeoutMs)
      let res
      try {
        res = await this.#fetch(this.#baseUrl + path, {
          method,
          headers: {
            Authorization: this.#apiKey, // the raw key, no "Bearer" prefix
            ...(payload && { "Content-Type": "application/json" }),
          },
          body: payload,
          signal: attemptSignal,
        })
      } catch (cause) {
        if (signal?.aborted) throw signal.reason // the caller gave up: never retry
        if (attempt >= this.maxAttempts) {
          throw new Api2PdfError(`${path}: ${cause.name === "TimeoutError" ? "timed out" : cause.message}`,
            { operation: path, retryable: true, cause })
        }
        await sleep(backoff(attempt), signal)
        continue
      }
      if (!RETRYABLE_STATUS.has(res.status) || attempt >= this.maxAttempts) return res
      await res.body?.cancel()
      await sleep(retryAfterMs(res) ?? backoff(attempt), signal)
    }
  }

  async #errorFrom(res, operation) {
    const data = await res.json().catch(() => ({}))
    return new Api2PdfError(`${operation}: ${data.Error ?? `HTTP ${res.status}`}`,
      { operation, status: res.status, responseId: data.ResponseId,
        retryable: RETRYABLE_STATUS.has(res.status) })
  }
}

function stripSignal({ signal, ...rest }) {
  return rest // undefined values are dropped by JSON.stringify, so API defaults apply
}

// Exponential backoff with full jitter: 0-1 s, 0-2 s, 0-4 s, capped at 10 s.
function backoff(attempt) {
  return Math.random() * Math.min(10_000, 1000 * 2 ** (attempt - 1))
}

function retryAfterMs(res) {
  const value = res.headers.get("retry-after")
  if (!value) return undefined
  const seconds = Number(value)
  if (Number.isFinite(seconds)) return Math.min(seconds * 1000, 30_000)
  const date = Date.parse(value)
  return Number.isNaN(date) ? undefined : Math.min(Math.max(0, date - Date.now()), 30_000)
}

Request bodies use the API's own field names, so anything from the Headless Chrome options (options.landscape, options.marginTop, options.puppeteerWaitForMethod and so on), fileName, inline, extraHTTPHeaders and useCustomStorage/storage passes straight through. Values you leave undefined are dropped by JSON.stringify, so the API defaults apply. Two names are worth knowing: the password endpoint spells its fields userpassword and ownerpassword, and extract-pages takes 0-based, inclusive start and end that may be negative (-1 is the last page).

Step 3: an HTML template that escapes by default

You do not need a template engine to build safe HTML in Node. A ten-line tagged template escapes every interpolated value unless it is itself an html`` fragment, so nested rows and arrays compose naturally and a customer named <script> prints as text. If you already use EJS, Handlebars, Nunjucks or React's renderToStaticMarkup, keep it; all the client needs is a string.

// src/html.js: a tagged template that HTML-escapes every interpolated value.
const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }

export class SafeHtml {
  constructor(value) { this.value = value }
  toString() { return this.value }
}

const escape = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ESCAPES[c])

function render(v) {
  if (v instanceof SafeHtml) return v.value
  if (Array.isArray(v)) return v.map(render).join("")
  return escape(v)
}

/** html`<p>${name}</p>` escapes name; nest html`` fragments and arrays freely. */
export function html(strings, ...values) {
  return new SafeHtml(strings.reduce((out, s, i) => out + s + (i < values.length ? render(values[i]) : ""), ""))
}
// src/invoice.js: the invoice template and the Chrome page setup that goes with it.
import { html } from "./html.js"

const money = (cents, currency) =>
  new Intl.NumberFormat("en-US", { style: "currency", currency }).format(cents / 100)

export function invoiceHtml(inv) {
  const total = inv.lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0)
  return html`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Invoice ${inv.number}</title>
<style>
  @page { size: A4; margin: 18mm 16mm 22mm; }
  body { font: 11pt/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #1f2937; }
  header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 28px; }
  h1 { font-size: 22pt; margin: 0; }
  .muted { color: #6b7280; }
  table { width: 100%; border-collapse: collapse; }
  thead { display: table-header-group; }   /* repeat the header row on every page */
  th, td { padding: 8px 6px; border-bottom: 1px solid #e5e7eb; text-align: left; }
  td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
  tr { break-inside: avoid; }               /* never split a row across pages */
  tfoot td { font-weight: 600; border-top: 2px solid #111827; border-bottom: 0; }
</style>
</head>
<body>
  <header>
    <div>
      <h1>Invoice ${inv.number}</h1>
      <div class="muted">Issued ${inv.issuedOn} &middot; Due ${inv.dueOn}</div>
    </div>
    <div style="text-align:right">
      <strong>${inv.customer.name}</strong><br>
      ${inv.customer.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>
      ${inv.lines.map((l) => html`<tr>
        <td>${l.description}</td>
        <td class="num">${l.qty}</td>
        <td class="num">${money(l.unitCents, inv.currency)}</td>
        <td class="num">${money(l.qty * l.unitCents, inv.currency)}</td>
      </tr>`)}
    </tbody>
    <tfoot><tr><td colspan="3">Total</td><td class="num">${money(total, inv.currency)}</td></tr></tfoot>
  </table>
</body>
</html>`.toString()
}

// One place for page setup, so downloads, jobs and exports produce the same document.
export const invoicePdfOptions = (inv) => ({
  fileName: `invoice-${inv.number}.pdf`,
  options: {
    preferCSSPageSize: true,
    printBackground: true,
    displayHeaderFooter: true,
    headerTemplate: "<span></span>",
    // Chrome renders the footer in its own context: inline styles and an explicit font-size.
    footerTemplate: `<div style="font-size:8pt;width:100%;text-align:center;color:#6b7280;">
      Invoice ${inv.number.replace(/[^\w-]/g, "")} &middot; page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`,
  },
})

Headless Chrome renders flexbox, grid and web fonts the way your browser does. A few print rules help long documents: @page sets the paper size and margins, preferCSSPageSize tells Chrome to honour it, display: table-header-group repeats the table header on every page, and break-inside: avoid keeps a row from splitting across pages. Chrome renders footerTemplate in its own context, so it needs inline styles and an explicit font-size, and it fills pageNumber and totalPages for you. The footer is plain string interpolation, so the invoice number is reduced to safe characters first. The page setup lives in one function so the download route and the batch job produce the same document. A stand-in for your database:

// src/invoices.js: stand-in for your database.
const INVOICES = new Map([
  ["2026-0042", {
    number: "2026-0042", issuedOn: "2026-11-02", dueOn: "2026-12-02", currency: "USD",
    customer: { id: "cus_acme", name: "Acme <Robotics> & Co.", email: "[email protected]" },
    lines: [
      { description: "Pro plan, November", qty: 1, unitCents: 4900 },
      { description: "Extra seats", qty: 3, unitCents: 900 },
    ],
  }],
])

export async function findInvoice(number) {
  return INVOICES.get(number) ?? null
}

export async function invoicesForCustomer(customerId, year) {
  return [...INVOICES.values()].filter((i) => i.customer.id === customerId && i.issuedOn.startsWith(String(year)))
}

Step 4: stream the PDF from an Express 5 route

Express 5 forwards rejected promises from async handlers to the error middleware, so the route needs no try/catch. Two details make it production-grade. The response body from fetch is a web ReadableStream; Readable.fromWeb plus pipeline pipes it to the client with backpressure, so a 40 MB report never sits in memory. And if the visitor closes the tab before the render finishes, the close listener aborts the request to Api2Pdf instead of letting it run to completion for nobody.

// src/app.js: the Express 5 app. Exported without listen() so tests can start it on a random port.
import express from "express"
import { Readable } from "node:stream"
import { pipeline } from "node:stream/promises"
import { Api2PdfError } from "./api2pdf.js"
import { invoiceHtml, invoicePdfOptions } from "./invoice.js"
import { findInvoice } from "./invoices.js"

export function createApp({ api2pdf, log = console }) {
  const app = express()

  app.get("/invoices/:number.pdf", async (req, res) => {
    const inv = await findInvoice(req.params.number)
    if (!inv) return res.status(404).json({ error: "invoice not found" })
    // (your auth check goes here: can this user see this invoice?)

    // Stop paying for a render nobody will read: abort if the client disconnects.
    const abort = new AbortController()
    res.on("close", () => { if (!res.writableFinished) abort.abort() })

    const pdf = await api2pdf.htmlToPdfStream(invoiceHtml(inv), {
      ...invoicePdfOptions(inv), signal: abort.signal,
    })
    const disposition = req.query.download !== undefined ? "attachment" : "inline"
    res.set({
      "Content-Type": "application/pdf",
      "Content-Disposition": `${disposition}; filename="invoice-${inv.number}.pdf"`,
      "Cache-Control": "private, no-store",
    })
    await pipeline(Readable.fromWeb(pdf), res)
  })

  // A readiness probe that also proves the key works. Do not expose it publicly.
  app.get("/internal/api2pdf", async (req, res) => {
    res.json(await api2pdf.balance({ signal: AbortSignal.timeout(5000) }))
  })

  // Express 5 sends rejected promises from async handlers here.
  app.use((err, req, res, next) => {
    if (err.name === "AbortError") return // the client went away
    if (err instanceof Api2PdfError) {
      log.error(`api2pdf ${err.operation} failed: status=${err.status} responseId=${err.responseId}: ${err.message}`)
      if (res.headersSent) return res.destroy(err)
      return res.status(502).json({ error: "PDF generation failed", responseId: err.responseId })
    }
    next(err)
  })

  return app
}
// src/server.js
import { Api2PdfClient } from "./api2pdf.js"
import { createApp } from "./app.js"

const api2pdf = new Api2PdfClient({ apiKey: process.env.API2PDF_API_KEY })
const port = Number(process.env.PORT ?? 3000)
createApp({ api2pdf }).listen(port, () => console.log(`listening on http://localhost:${port}`))
npm start
curl -o invoice.pdf 'http://localhost:3000/invoices/2026-0042.pdf?download'

Cache-Control: private, no-store keeps invoices out of shared caches. Add your authorization check where the comment is: the route renders whatever invoice number it is given. The /internal/api2pdf route calls GET /balance, a cheap way to prove at deploy time that the key in this environment is valid; keep it behind your internal network or admin auth.

Step 5: merge, watermark and password-protect a statement packet

A year-end statement is a good example of chaining. Render one PDF per invoice with a small concurrency limit, merge them in order, optionally stamp DRAFT diagonally on every page with the watermark endpoint, and finally encrypt the result with a user and owner password. Every step takes the previous step's FileUrl, so no bytes travel through your server. The finally block deletes every intermediate with DELETE /file/{responseId}, because unencrypted copies of a customer's invoices should not stay online for 24 hours, and it runs on failure too.

// src/packet.js: render many invoices, merge them, stamp DRAFT, lock with a password,
// land the result in S3, and clean up every intermediate file.
import { invoiceHtml, invoicePdfOptions } from "./invoice.js"

// Run fn over items with at most `limit` requests in flight, preserving order.
async function mapLimit(items, limit, fn) {
  const results = new Array(items.length)
  let next = 0
  const worker = async () => {
    while (next < items.length) {
      const i = next++
      results[i] = await fn(items[i], i)
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
  return results
}

export async function buildStatementPacket(api2pdf, {
  invoices, userPassword, ownerPassword, draft = false, upload, concurrency = 4, signal, log = console,
}) {
  if (invoices.length === 0) throw new Error("no invoices to include")
  const temporary = [] // ResponseIds of hosted intermediates, deleted at the end
  let cost = 0          // every JSON response reports what the call cost, in USD
  const track = (result) => { temporary.push(result.ResponseId); cost += result.Cost ?? 0; return result }

  try {
    // 1. One PDF per invoice, hosted by Api2Pdf for up to 24 hours.
    const rendered = await mapLimit(invoices, concurrency, (inv) =>
      api2pdf.htmlToPdf(invoiceHtml(inv), { ...invoicePdfOptions(inv), signal }).then(track))

    // 2. Merge in order. PdfSharp reads its inputs from URLs, so FileUrl chains directly.
    let current = track(await api2pdf.merge(rendered.map((r) => r.FileUrl), { signal }))

    // 3. Optional diagonal stamp on every page.
    if (draft) {
      current = track(await api2pdf.watermark(current.FileUrl, {
        text: "DRAFT", fontSize: 96, color: "#B91C1C", opacity: 0.12, rotation: -45, signal,
      }))
    }

    // 4. Encrypt, and have Api2Pdf PUT the final file straight into your bucket.
    const final = await api2pdf.password(current.FileUrl, {
      userPassword, ownerPassword, fileName: "statement.pdf", ...upload, signal,
    })
    cost += final.Cost ?? 0
    log.info?.(`packet ready: ${invoices.length} invoices, final ResponseId ${final.ResponseId}`)
    return { responseId: final.ResponseId, fileUrl: upload ? null : final.FileUrl, cost }
  } finally {
    // Unencrypted copies should not outlive the job. Deletes are best effort.
    const results = await Promise.allSettled(temporary.map((id) => api2pdf.deleteFile(id)))
    results.filter((r) => r.status === "rejected")
      .forEach((r) => log.warn?.(`cleanup failed: ${r.reason.message}`))
  }
}
  • Watermark options. text defaults to DRAFT, fontSize to 72, color to #000000, opacity to 0.15 and rotation to -45 degrees. The values above make a large, faint red stamp.
  • Concurrency. Four requests in flight is a sensible default for a background job: fast enough for hundreds of invoices, gentle on your outbound connections. Raise it for bulk exports; the retry logic handles a 429 if you overdo it.
  • Cost tracking. Each JSON response reports what the call cost, so the job returns the total and you can attribute PDF spend per customer or feature.
  • One page only. Need just the summary page for an email preview? api2pdf.extractPages(fileUrl, { start: 0, end: 0 }) returns a PDF with the first page, and { start: -1 } the last.

Step 6: write the final PDF straight into S3 with useCustomStorage

When the PDF belongs in your bucket, downloading it from Api2Pdf only to upload it again wastes bandwidth and time. Presign a PUT for the exact object key and pass it as storage with useCustomStorage: true; Api2Pdf uploads the file there. The same shape works with a Google Cloud Storage signed URL or an Azure SAS URL.

// src/s3.js: a presigned PUT that Api2Pdf can upload the finished PDF to.
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3"
import { getSignedUrl } from "@aws-sdk/s3-request-presigner"

// Region and credentials come from the environment or the IAM role.
// WHEN_REQUIRED stops SDK v3 (3.729+) from signing a CRC32 of an empty body into the URL,
// which would make S3 reject the real PDF with a checksum mismatch.
const s3 = new S3Client({ requestChecksumCalculation: "WHEN_REQUIRED" })

export async function presignPdfUpload(bucket, key, expiresIn = 900) {
  const url = await getSignedUrl(
    s3,
    new PutObjectCommand({ Bucket: bucket, Key: key, ContentType: "application/pdf" }),
    { expiresIn, signableHeaders: new Set(["content-type"]) },
  )
  // content-type is now part of the signature, so the upload must send exactly this value.
  return {
    useCustomStorage: true,
    storage: { method: "PUT", url, extraHTTPHeaders: { "Content-Type": "application/pdf" } },
  }
}
  • The checksum trap. Since version 3.729, AWS SDK for JavaScript v3 adds default integrity checksums: a presigned PutObject URL now carries x-amz-checksum-crc32 and x-amz-sdk-checksum-algorithm computed over an empty body, and S3 rejects the real upload. requestChecksumCalculation: "WHEN_REQUIRED" on the client turns that off for presigning.
  • Signed headers must match. signableHeaders makes content-type part of the signature, so the object is stored as application/pdf and nobody can upload something else with that URL. Api2Pdf then has to send the same header, which is what storage.extraHTTPHeaders is for. Drop both if you do not care about the content type.
  • Keep the expiry short. The URL is used once, within seconds. Fifteen minutes leaves room for retries.

The export script ties it together, with a ten-minute budget for the whole job passed down as one AbortSignal:

// src/export-statement.js: node --env-file=.env src/export-statement.js cus_acme 2026
import { Api2PdfClient } from "./api2pdf.js"
import { invoicesForCustomer } from "./invoices.js"
import { buildStatementPacket } from "./packet.js"
import { presignPdfUpload } from "./s3.js"

const [customerId, year] = process.argv.slice(2)
const api2pdf = new Api2PdfClient({ apiKey: process.env.API2PDF_API_KEY })
const invoices = await invoicesForCustomer(customerId, year)
const key = `statements/${year}/${customerId}.pdf`

const result = await buildStatementPacket(api2pdf, {
  invoices,
  userPassword: process.env.STATEMENT_PASSWORD, // e.g. sent to the customer out of band
  ownerPassword: process.env.STATEMENT_OWNER_PASSWORD,
  upload: await presignPdfUpload(process.env.STATEMENTS_BUCKET, key),
  signal: AbortSignal.timeout(10 * 60_000), // budget for the whole job
})
console.log(`s3://${process.env.STATEMENTS_BUCKET}/${key}`, result)
node --env-file=.env src/export-statement.js cus_acme 2026

Step 7: test without the network

The client takes a baseUrl, so tests point it at a local HTTP server that records each request and answers like Api2Pdf. No mocking library, no network, no API credit:

// test/fake-api2pdf.js: a local stand-in for v2.api2pdf.com that records every request.
import http from "node:http"

export async function startFakeApi2Pdf(handler) {
  const requests = []
  const server = http.createServer(async (req, res) => {
    let raw = ""
    for await (const chunk of req) raw += chunk
    const call = { method: req.method, url: req.url, headers: req.headers, body: raw ? JSON.parse(raw) : undefined }
    requests.push(call)
    const reply = (await handler(call, requests.length)) ?? ok(call)
    if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs))
    if (res.destroyed) return
    res.writeHead(reply.status ?? 200, { "Content-Type": reply.type ?? "application/json", ...reply.headers })
    res.end(reply.raw ?? JSON.stringify(reply.json))
  })
  await new Promise((r) => server.listen(0, "127.0.0.1", r))
  return {
    baseUrl: `http://127.0.0.1:${server.address().port}`,
    requests,
    close: () => new Promise((r) => { server.closeAllConnections(); server.close(r) }),
  }
}

let n = 0
export function ok(call) {
  if (call.url.includes("outputBinary=true")) {
    return { type: "application/pdf", raw: Buffer.from("%PDF-1.7\n% fake pdf\n%%EOF\n") }
  }
  const id = `resp-${++n}`
  return { json: { Success: true, Error: null, FileUrl: `https://storage.example/${id}.pdf`, ResponseId: id, MbOut: 0.05, Seconds: 1.2, Cost: 0.001 } }
}

export const fail = (status, error) => ({
  status, json: { Success: false, Error: error, FileUrl: null, ResponseId: `err-${status}`, MbOut: 0, Seconds: 0, Cost: 0 },
})
// test/api2pdf.test.js
import { test } from "node:test"
import assert from "node:assert/strict"
import { Api2PdfClient, Api2PdfError } from "../src/api2pdf.js"
import { startFakeApi2Pdf, fail } from "./fake-api2pdf.js"

const client = (baseUrl, extra) => new Api2PdfClient({ apiKey: "test-key", baseUrl, ...extra })

test("sends the raw key and a JSON body, returns the result", async (t) => {
  const api = await startFakeApi2Pdf(() => {})
  t.after(api.close)
  const result = await client(api.baseUrl).htmlToPdf("<p>hi</p>", { fileName: "a.pdf", inline: false })
  const [call] = api.requests
  assert.equal(call.url, "/chrome/pdf/html")
  assert.equal(call.headers.authorization, "test-key")
  assert.deepEqual(call.body, { html: "<p>hi</p>", fileName: "a.pdf", inline: false })
  assert.match(result.FileUrl, /^https:\/\//)
})

test("retries 503 and honours Retry-After", async (t) => {
  const api = await startFakeApi2Pdf((call, i) => (i === 1 ? { ...fail(503, "busy"), headers: { "Retry-After": "0" } } : undefined))
  t.after(api.close)
  const result = await client(api.baseUrl).merge(["https://x.example/a.pdf"])
  assert.equal(api.requests.length, 2)
  assert.equal(result.Success, true)
})

test("does not retry a 401 and surfaces the ResponseId", async (t) => {
  const api = await startFakeApi2Pdf(() => fail(401, "Invalid API key"))
  t.after(api.close)
  await assert.rejects(client(api.baseUrl).htmlToPdf("<p>x</p>"), (err) => {
    assert.ok(err instanceof Api2PdfError)
    assert.equal(err.status, 401)
    assert.equal(err.responseId, "err-401")
    assert.match(err.message, /Invalid API key/)
    return true
  })
  assert.equal(api.requests.length, 1)
})

test("a 200 with Success:false is still an error", async (t) => {
  const api = await startFakeApi2Pdf(() => ({ json: { Success: false, Error: "Could not load url", ResponseId: "r1" } }))
  t.after(api.close)
  await assert.rejects(client(api.baseUrl).urlToPdf("https://example.com"), /Could not load url/)
})

test("times out each attempt and gives up after maxAttempts", async (t) => {
  const api = await startFakeApi2Pdf(() => ({ delayMs: 500 }))
  t.after(api.close)
  await assert.rejects(client(api.baseUrl, { attemptTimeoutMs: 50, maxAttempts: 2 }).htmlToPdf("<p>x</p>"), /timed out/)
  assert.equal(api.requests.length, 2)
})

test("a caller abort is never retried", async (t) => {
  const api = await startFakeApi2Pdf(() => ({ delayMs: 500 }))
  t.after(api.close)
  await assert.rejects(client(api.baseUrl).htmlToPdf("<p>x</p>", { signal: AbortSignal.timeout(50) }), { name: "TimeoutError" })
  assert.equal(api.requests.length, 1)
})

test("binary errors arrive as JSON and become Api2PdfError", async (t) => {
  const api = await startFakeApi2Pdf(() => fail(400, "html is required"))
  t.after(api.close)
  await assert.rejects(client(api.baseUrl).htmlToPdfStream(""), { name: "Api2PdfError", status: 400 })
  assert.match(api.requests[0].url, /outputBinary=true/)
})

test("password uses the lowercase field names; deleteFile and balance hit the utility routes", async (t) => {
  const api = await startFakeApi2Pdf((call) => (call.url === "/balance" ? { json: { Success: true } } : undefined))
  t.after(api.close)
  const c = client(api.baseUrl)
  await c.password("https://x.example/a.pdf", { userPassword: "u", ownerPassword: "o" })
  await c.extractPages("https://x.example/a.pdf", { start: 0, end: 0 })
  await c.deleteFile("abc 123")
  await c.balance()
  assert.deepEqual(api.requests[0].body, { url: "https://x.example/a.pdf", userpassword: "u", ownerpassword: "o" })
  assert.deepEqual(api.requests[1].body, { url: "https://x.example/a.pdf", start: 0, end: 0 })
  assert.equal(api.requests[2].method, "DELETE")
  assert.equal(api.requests[2].url, "/file/abc%20123")
  assert.deepEqual([api.requests[3].method, api.requests[3].url], ["GET", "/balance"])
})

The Express app is created without listen(), so a test can start it on port 0 and call it with fetch:

// test/app.test.js
import { test } from "node:test"
import assert from "node:assert/strict"
import { Api2PdfClient } from "../src/api2pdf.js"
import { createApp } from "../src/app.js"
import { startFakeApi2Pdf, fail } from "./fake-api2pdf.js"

const quiet = { error() {}, info() {}, warn() {} }

async function startApp(t, handler) {
  const api = await startFakeApi2Pdf(handler)
  const api2pdf = new Api2PdfClient({ apiKey: "test-key", baseUrl: api.baseUrl, maxAttempts: 1 })
  const server = createApp({ api2pdf, log: quiet }).listen(0)
  await new Promise((r) => server.once("listening", r))
  t.after(() => { server.close(); return api.close() })
  return { api, url: `http://127.0.0.1:${server.address().port}` }
}

test("streams the invoice PDF with escaped customer data", async (t) => {
  const { api, url } = await startApp(t, () => {})
  const res = await fetch(`${url}/invoices/2026-0042.pdf?download`)
  assert.equal(res.status, 200)
  assert.equal(res.headers.get("content-type"), "application/pdf")
  assert.equal(res.headers.get("content-disposition"), 'attachment; filename="invoice-2026-0042.pdf"')
  assert.ok((await res.text()).startsWith("%PDF"))
  const sent = api.requests[0].body
  assert.ok(sent.html.includes("Acme &lt;Robotics&gt; &amp; Co."))
  assert.ok(sent.html.includes("$76.00")) // 49 + 3 x 9
  assert.equal(sent.options.preferCSSPageSize, true)
})

test("returns 404 for an unknown invoice without calling Api2Pdf", async (t) => {
  const { api, url } = await startApp(t, () => {})
  const res = await fetch(`${url}/invoices/nope.pdf`)
  assert.equal(res.status, 404)
  assert.equal(api.requests.length, 0)
})

test("maps an Api2Pdf failure to 502 with the ResponseId", async (t) => {
  const { url } = await startApp(t, () => fail(401, "Invalid API key"))
  const res = await fetch(`${url}/invoices/2026-0042.pdf`)
  assert.equal(res.status, 502)
  assert.deepEqual(await res.json(), { error: "PDF generation failed", responseId: "err-401" })
})
// test/packet.test.js
import { test } from "node:test"
import assert from "node:assert/strict"
import { Api2PdfClient } from "../src/api2pdf.js"
import { buildStatementPacket } from "../src/packet.js"
import { startFakeApi2Pdf, fail } from "./fake-api2pdf.js"

const inv = (n) => ({
  number: `2026-${n}`, issuedOn: "2026-01-01", dueOn: "2026-02-01", currency: "USD",
  customer: { id: "c", name: "C", email: "[email protected]" }, lines: [{ description: "x", qty: 1, unitCents: 100 }],
})
const quiet = { info() {}, warn() {} }
const upload = { useCustomStorage: true, storage: { method: "PUT", url: "https://bucket.example/k?sig=1", extraHTTPHeaders: { "Content-Type": "application/pdf" } } }

test("render -> merge -> watermark -> password to S3, then delete intermediates", async (t) => {
  const api = await startFakeApi2Pdf(() => {})
  t.after(api.close)
  const c = new Api2PdfClient({ apiKey: "k", baseUrl: api.baseUrl })
  const result = await buildStatementPacket(c, {
    invoices: [inv(1), inv(2), inv(3)], userPassword: "u", ownerPassword: "o", draft: true, upload, log: quiet,
  })
  const urls = api.requests.map((r) => `${r.method} ${r.url}`)
  assert.deepEqual(urls.slice(0, 3), Array(3).fill("POST /chrome/pdf/html"))
  assert.deepEqual(urls.slice(3, 6), ["POST /pdfsharp/merge", "POST /pdfsharp/watermark", "POST /pdfsharp/password"])
  assert.equal(urls.filter((u) => u.startsWith("DELETE /file/")).length, 5)

  const [merge, watermark, password] = api.requests.slice(3, 6).map((r) => r.body)
  assert.equal(merge.urls.length, 3)
  assert.match(watermark.url, /^https:\/\/storage\.example\/resp-\d+\.pdf$/) // the merge result
  assert.ok(!merge.urls.includes(watermark.url))
  assert.equal(watermark.text, "DRAFT")
  assert.equal(password.userpassword, "u")
  assert.deepEqual(password.storage, upload.storage)
  assert.equal(password.useCustomStorage, true)
  assert.equal(result.fileUrl, null)
  assert.ok(result.cost > 0)
})

test("cleans up even when a step fails", async (t) => {
  const api = await startFakeApi2Pdf((call) => (call.url === "/pdfsharp/merge" ? fail(400, "bad pdf") : undefined))
  t.after(api.close)
  const c = new Api2PdfClient({ apiKey: "k", baseUrl: api.baseUrl })
  await assert.rejects(buildStatementPacket(c, { invoices: [inv(1), inv(2)], userPassword: "u", log: quiet }), /bad pdf/)
  assert.equal(api.requests.filter((r) => r.method === "DELETE").length, 2)
})
$ npm test
✔ sends the raw key and a JSON body, returns the result
✔ retries 503 and honours Retry-After
✔ does not retry a 401 and surfaces the ResponseId
✔ a 200 with Success:false is still an error
✔ times out each attempt and gives up after maxAttempts
✔ a caller abort is never retried
✔ binary errors arrive as JSON and become Api2PdfError
✔ password uses the lowercase field names; deleteFile and balance hit the utility routes
✔ streams the invoice PDF with escaped customer data
✔ returns 404 for an unknown invoice without calling Api2Pdf
✔ maps an Api2Pdf failure to 502 with the ResponseId
✔ render -> merge -> watermark -> password to S3, then delete intermediates
✔ cleans up even when a step fails
ℹ tests 13
ℹ pass 13

Production notes

  • Keep the key server-side. Never call Api2Pdf from browser JavaScript; the key in the Authorization header would be visible to every visitor. Go through a route that authorizes the user first.
  • Reuse one client. Create the Api2PdfClient once at startup and share it. Node's fetch (undici) pools and keeps alive connections to v2.api2pdf.com across requests.
  • Pick the right path for each document. Stream small documents from the route; move big, bulk or chained work such as the statement packet to a queue worker (BullMQ, SQS, a cron job), and use useCustomStorage when the result belongs in your bucket anyway.
  • Serverless is a good fit. The client has no dependencies and no binaries, so it runs unchanged on AWS Lambda, Vercel Functions or Cloud Run. Give the function a timeout above the attempt timeout, or lower attemptTimeoutMs and maxAttempts to fit the platform's limit. For Cloudflare Workers see this post.
  • 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: "https://v2-xl.api2pdf.com" (4 CPU, 8 GB, 5 minute limit, priced at 10x the standard rate) and an attemptTimeoutMs of about 360,000. 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 with deleteFile, or skip the hosted copy with useCustomStorage.
  • 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, MbOut and Cost. 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 Bearer prefix, check for a trailing newline in the environment variable, and confirm the deployed environment sets API2PDF_API_KEY.
  • 402 Payment Required with an x402Version body. The request reached Api2Pdf with no Authorization header at all, usually because process.env.API2PDF_API_KEY was undefined in that process. Unauthenticated requests are offered x402 pay-per-request instead. The client's constructor refuses an empty key for this reason.
  • TimeoutError or timed out. The document needs more than the attempt timeout. Look for slow external assets or a long delay, or move the job to V2 XL.
  • Styles or images missing. The CSS or image is on a host Api2Pdf cannot reach, such as localhost, a private network or a route behind your login. Inline the CSS and use public absolute URLs or data: URIs for images.
  • Charts or client-rendered content is blank. Chrome printed before your JavaScript finished. Set options.delay (milliseconds) or wait with puppeteerWaitForMethod and puppeteerWaitForValue, as described in the Headless Chrome options. Better still, render charts as SVG on the server.
  • 403 in a merge, watermark or password call. Api2Pdf could not download one of the input URLs. Use the FileUrl values directly, or presigned URLs, and see this post if the files live on your own server.
  • SignatureDoesNotMatch or a checksum error from S3. A signed header was not sent with the same value, the URL expired, or the SDK signed a checksum into the URL. Check extraHTTPHeaders and requestChecksumCalculation as in Step 6.
  • Readable.fromWeb is not a function. You are on Node 16 or older. Upgrade to a supported LTS release.

Wrap-up

You now have a Node.js PDF pipeline with no Chromium to install: an escaping HTML template, a dependency-free fetch client with timeouts, retries and cancellation, an Express 5 route that streams PDFs without buffering them, a statement job that merges, watermarks and encrypts a packet, writes it straight into S3 and cleans up after itself, 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, barcodes and QR codes, 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.