0

Get PDF

by
Published today

Render a page (url or raw html) to a PDF, returned base64-encoded so Windmill previews it. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).

Script cloudflare Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 3 hours ago
1
//native
2

3
/**
4
 * Get PDF
5
 * Render a page (url or raw html) to a PDF, returned base64-encoded so Windmill previews it. Extra fields go in options (gotoOptions, viewport, waitForSelector, userAgent, ...).
6
 */
7
export async function main(
8
  auth: RT.Cloudflare,
9
  url: string | undefined,
10
  html: string | undefined,
11
  options: { [key: string]: any } | undefined
12
) {
13
  if (!url && !html) throw new Error("Either url or html is required")
14

15
  const response = await fetch(
16
    `https://api.cloudflare.com/client/v4/accounts/${auth.account_id}/browser-rendering/pdf`,
17
    {
18
      method: "POST",
19
      headers: {
20
        Authorization: `Bearer ${auth.token}`,
21
        "Content-Type": "application/json",
22
      },
23
      body: JSON.stringify({
24
        url: url || undefined,
25
        html: html || undefined,
26
        ...options,
27
      }),
28
    }
29
  )
30

31
  if (!response.ok) {
32
    throw new Error(`${response.status} ${await response.text()}`)
33
  }
34

35
  const bytes = new Uint8Array(await response.arrayBuffer())
36
  let binary = ""
37
  for (let i = 0; i < bytes.length; i += 0x8000) {
38
    binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
39
  }
40
  // Windmill renders { pdf: <base64> } inline in the result panel.
41
  return { pdf: btoa(binary) }
42
}
43