/pdf エンドポイントは、Cloudflare のヘッドレス Browser Run サービスを使い、ブラウザーにウェブページまたはカスタム HTML の PDF を生成させます。
このエンドポイントは、次の 2 通りの方法で使えます。
- REST API:
Browser Rendering - Edit権限を持つ カスタム API トークンを作成 します。 - Workers Bindings: Workers Bindings を使い、Cloudflare Worker から直接エンドポイントを呼び出します。API トークンは不要です。
詳細は Quick Actions: 始める前に を参照してください。
https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdfurl または html のいずれかを指定します。
url(string)html(string)
- ウェブページの PDF を取得する
- 請求書、ライセンス、レポート、証明書などの PDF を HTML から直接生成する
https://example.com/ に移動し、カスタム CSS と外部スタイルシートを注入します。その後、レンダリングしたページを PDF として返します。
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf' \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://example.com/",
"addStyleTag": [
{ "content": "body { font-family: Arial; }" }
]
}' \
--output "output.pdf"import Cloudflare from "cloudflare";
const client = new Cloudflare({
apiToken: process.env["CLOUDFLARE_API_TOKEN"],
});
const pdf = await client.browserRendering.pdf.create({
account_id: process.env["CLOUDFLARE_ACCOUNT_ID"],
url: "https://example.com/",
addStyleTag: [{ content: "body { font-family: Arial; }" }],
});
console.log(pdf);
const content = await pdf.blob();
console.log(content);interface Env {
BROWSER: BrowserRun;
}
export default {
async fetch(request, env): Promise<Response> {
return await env.BROWSER.quickAction("pdf", {
url: "https://example.com/",
addStyleTag: [{ content: "body { font-family: Arial; }" }],
});
},
} satisfies ExportedHandler<Env>;生の HTML から PDF を生成したい場合は、html オプションを使います。addStyleTag パラメーターでカスタムスタイルも適用できます。
curl -X POST https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"html": "<html><body>Advanced Snapshot</body></html>",
"addStyleTag": [
{ "content": "body { font-family: Arial; }" },
{ "url": "https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" }
]
}' \
--output "invoice.pdf"https://example.com に移動し、追加の HTTP ヘッダーを設定してページサイズ(ビューポート)を指定します。PDF 生成は、ネットワーク接続が 2 本以下の状態が少なくとも 500 ms 続くまで、または最大タイムアウト 4500 ms に達するまで待ってからレンダリングします。
goToOptions パラメーターは Puppeteer の API ↗ のほとんどを公開します。
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf' \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://example.com/",
"setExtraHTTPHeaders": {
"X-Custom-Header": "value"
},
"viewport": {
"width": 1200,
"height": 800
},
"gotoOptions": {
"waitUntil": "networkidle2",
"timeout": 45000
}
}' \
--output "advanced-output.pdf"レンダリング中のリクエストをブロックするには、rejectResourceTypes と rejectRequestPattern を使えます。逆に、allowResourceTypes と allowRequestPattern で特定のリクエストだけを許可することもできます。
curl -X POST https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://cloudflare.com/",
"rejectResourceTypes": ["image"],
"rejectRequestPattern": ["/^.*\\.(css)"]
}' \
--output "cloudflare.pdf"headerTemplate と footerTemplate で HTML テンプレートを使い、ページのヘッダーとフッターをカスタマイズできます。出力に含めるには displayHeaderFooter を有効にします。次の例では、ブランド付きヘッダー、フッターメッセージ、ページ番号付きの A5 PDF を生成します。
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf' \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://example.com",
"pdfOptions": {
"format": "a5",
"headerTemplate": "<div style=\"font-size: 10px; text-align: center; width: 100%; padding: 5px;\"><span>brand name</span></div>",
"displayHeaderFooter": true,
"footerTemplate": "<div style=\"color: lightgray; border-top: solid lightgray 1px; font-size: 10px; padding-top: 5px; text-align: center; width: 100%;\"><span>This is a test message</span> - <span class=\"pageNumber\"></span></div>",
"margin": {
"top": "70px",
"bottom": "70px"
}
}
}' \
--output "header-footer.pdf"ヘッダーやフッターに title、date、pageNumber、totalPages などの動的プレースホルダーを含め、各ページにメタデータを表示できます。次の例では、会社ブランドのヘッダー、現在の日付とタイトル、フッターのページ番号付きの A4 PDF を生成します。
curl -X POST 'https://api.cloudflare.com/client/v4/accounts/<accountId>/browser-rendering/pdf' \
-H 'Authorization: Bearer <apiToken>' \
-H 'Content-Type: application/json' \
-d '{
"url": "https://news.ycombinator.com",
"pdfOptions": {
"format": "a4",
"landscape": false,
"printBackground": true,
"preferCSSPageSize": true,
"displayHeaderFooter": true,
"scale": 1.0,
"headerTemplate": "<div style=\"width: 100%; font-size: 10px; padding: 10px; text-align: center;\"><div style=\"border-bottom: 1px solid #ddd;\"><span style=\"color: #666;\">Company Name</span> | <span class=\"date\"></span> | <span class=\"title\"></span></div></div>",
"footerTemplate": "<div style=\"width: 100%; font-size: 10px; padding: 10px; text-align: center;\"><div style=\"border-top: 1px solid #ddd;\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div></div>",
"margin": {
"top": "100px",
"bottom": "80px",
"right": "30px",
"left": "30px"
},
"timeout": 30000
}
}' \
--output "dynamic-header-footer.pdf"Browser Run 環境に事前インストールされていないフォントが PDF に必要な場合は、addStyleTag パラメーターでカスタムフォントを読み込めます。手順と例は 独自のカスタムフォントを使う を参照してください。
JavaScript が多いページや Single Page Application(SPA)では、デフォルトのページ読み込み動作だと、空または不完全な結果が返ることがあります。ブラウザーが、JavaScript によるコンテンツ描画が終わる前にページ読み込み完了とみなすためです。
いちばん簡単な対処は、gotoOptions.waitUntil パラメータを networkidle0 または networkidle2 に設定することです。
{
"url": "https://example.com",
"gotoOptions": {
"waitUntil": "networkidle0"
}
}より速い応答が必要な場合、上級者はネットワーク活動がすべて止まるのを待つのではなく、waitForSelector で特定の要素を待てます。必要なコンテンツが読み込まれたことを示す CSS セレクターを把握している必要があります。詳細は Quick Actions のタイムアウト を参照してください。
JSON 本文のトップレベルパラメーターとして userAgent を渡すと、ページ単位で User-Agent を変更できます。対象サイトが User-Agent に応じて別のコンテンツを返す場合に便利です。
質問がある場合やエラーが発生した場合は、Browser Run の FAQ とトラブルシューティングガイド を参照してください。