> ## Documentation Index
> Fetch the complete documentation index at: https://docs.doczilla.app/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate a PDF in the background

> Queue a render and store its signed webhook result once, even if delivery is retried.

Use [Create PDF async](https://docs.doczilla.app/api-reference/endpoint/async-pdf.md)
when you want to acknowledge a request before the PDF is ready. The API returns a job ID.
Save that ID with your app's report so you can look up its result later.

## Queue the PDF

With Node.js 24, install the [Doczilla Node SDK](https://docs.doczilla.app/libraries/nodejs.md)
and Express with `npm install @doczilla/node express`.

Save this as `queue-pdf.mjs` alongside `weekly-summary.html`. Set `DOCZILLA_API_KEY` and `DOCZILLA_WEBHOOK_URL`
to your server-side API key and the public HTTPS URL for the receiver below. This example uses `WebhookOptions.receiveType.BASE64`
so the receiver can store the PDF without a second download.

```javascript queue-pdf.mjs theme={null}
import { readFile } from 'node:fs/promises'
import Doczilla, { PdfOptions, WebhookOptions } from '@doczilla/node'

const { DOCZILLA_API_KEY, DOCZILLA_WEBHOOK_URL } = process.env
if (!DOCZILLA_API_KEY || !DOCZILLA_WEBHOOK_URL) {
  throw new Error('Set DOCZILLA_API_KEY and DOCZILLA_WEBHOOK_URL')
}

const html = await readFile(new URL('./weekly-summary.html', import.meta.url), 'utf8')
const doczilla = new Doczilla(DOCZILLA_API_KEY)
const { id, status } = await doczilla.pdf.async({
  page: { html },
  pdf: { format: PdfOptions.format.A4 },
  webhook: {
    url: DOCZILLA_WEBHOOK_URL,
    method: WebhookOptions.method.POST,
    receiveType: WebhookOptions.receiveType.BASE64
  }
})
console.log({ id, status })
```

The SDK encodes the HTML for you. A newly queued job returns `PENDING`.

## HTML

Save the HTML below as `weekly-summary.html`.

> [accordion] Weekly summary HTML
>
> <Snippet file="code-group/background-pdf-html.md" />

## Receive and store the result

Save this as `receive-pdf.mjs`. Keep `DOCZILLA_API_KEY`
in the environment to initialize the SDK and set `DOCZILLA_WEBHOOK_SECRET`
to the webhook secret in your organization settings. Start `node receive-pdf.mjs` and expose its `/webhooks/doczilla`
route over HTTPS before submitting the job.

The receiver uses the raw request body for the same [signature check](https://docs.doczilla.app/examples/securing-webhooks.md)
as the webhook security example. It then saves the PDF by job ID.

```javascript receive-pdf.mjs theme={null}
import { DatabaseSync } from 'node:sqlite'
import Doczilla, { WebhookEvent } from '@doczilla/node'
import express from 'express'

const { DOCZILLA_API_KEY, DOCZILLA_WEBHOOK_SECRET } = process.env
if (!DOCZILLA_API_KEY || !DOCZILLA_WEBHOOK_SECRET) {
  throw new Error('Set DOCZILLA_API_KEY and DOCZILLA_WEBHOOK_SECRET')
}

const doczilla = new Doczilla(DOCZILLA_API_KEY)

const db = new DatabaseSync('renders.sqlite')
db.exec('CREATE TABLE IF NOT EXISTS renders (id TEXT PRIMARY KEY, pdf BLOB NOT NULL)')
const savePdf = db.prepare('INSERT INTO renders (id, pdf) VALUES (?, ?) ON CONFLICT(id) DO NOTHING')

const app = express()
app.post('/webhooks/doczilla', express.raw({ type: 'application/json', limit: '8mb' }), (req, res) => {
  const signature = req.get('x-doczilla-signature')
  if (!Buffer.isBuffer(req.body) || !signature) {
    return res.sendStatus(400)
  }

  let event
  try {
    event = doczilla.webhook.verifyPayload(req.body.toString('utf8'), signature, DOCZILLA_WEBHOOK_SECRET)
  } catch {
    return res.sendStatus(400)
  }

  if (event?.status !== WebhookEvent.status.COMPLETED || typeof event.id !== 'string' || typeof event.fileBase64 !== 'string') {
    return res.sendStatus(400)
  }

  const pdf = Buffer.from(event.fileBase64, 'base64')
  if (!pdf.subarray(0, 5).equals(Buffer.from('%PDF-'))) {
    return res.sendStatus(400)
  }

  try {
    savePdf.run(event.id, pdf)
    return res.sendStatus(204)
  } catch (error) {
    console.error('Could not store PDF', error)
    return res.sendStatus(503)
  }
})

app.listen(4242)
```

The signed payload's `id` is the ID returned by the queue request. When a row with that ID exists in `renders`,
your app can mark the report ready and serve the saved PDF.
The primary key makes saving the result atomic even if the same webhook is delivered twice.
Both deliveries receive `204` once the result is stored.

## Handle a missing result

* **The queue request returns an error.** Keep the report in an error state. If the request timed out,
  check whether a job was created before submitting again.
* **The job stays pending in your app.** Set an application deadline and check the job by ID in the Doczilla dashboard.
  A render can fail before reaching the completion webhook.
  The dashboard also distinguishes render failures from delivery failures.
* **The PDF is too large for the receiver.** Use `WebhookOptions.receiveType.URL` and download `fileUrl`
  promptly after verifying the webhook. The URL expires after an hour.

See [Webhook options](https://docs.doczilla.app/api-reference/webhook-options.md) and [Securing your webhook](https://docs.doczilla.app/examples/securing-webhooks.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.