Node.js PDF生成完全ガイド|Express・サーバーレス・Honoで実装
「Node.jsでPDFを生成したい」という要件は、請求書・レポート・証明書・帳票など、あらゆるWebアプリで発生します。ライブラリを自前でインストールするか、APIを使うか、サーバーレスで動かすか――選択肢は複数あります。
この記事では、Node.jsプロジェクトでPDFを生成するすべての主要パターンを、実際に動くコード例とともに解説します。FUNBREW PDF APIを使う方法を中心に、Express・Hono・AWS Lambda・Cloudflare Workersでの実装まで幅広くカバーします。
Node.js でのPDF生成:4つのアプローチ比較
まず主要な手法を比較します。
| アプローチ | メリット | デメリット | おすすめ用途 |
|---|---|---|---|
| PDF API(FUNBREW PDF) | ブラウザのインストール不要・quality エンジン(Chromium、Pro プラン以上)でモダンなCSSに対応 | ネットワーク依存・プランごとの毎分/月間の上限 | 本番環境・SaaS |
| Puppeteer(ローカル) | 無料・細かい制御 | インストール時に Chrome for Testing(Linux で約282MB)をダウンロードする・サーバーレスではブラウザの同梱に工夫が要る | 開発・少量生成 |
| PDFKit | 依存が少ない(fontkit など数個) | HTMLではなく描画命令でページを組み立てる低水準API | シンプルな帳票 |
| jsPDF | ブラウザ(クライアントサイド)で動く | HTMLの変換(html())は html2canvas に依存し、CSSレイアウトの再現は要検証 |
軽量なクライアント生成 |
複雑なHTMLレイアウト(グラフ・テーブル・日本語フォント)を含む業務PDFでは、ブラウザを自前で運用しない PDF API が有力な選択肢です。PDF APIとライブラリの比較で詳しく解説しています。
インストールと基本設定
# プロジェクト初期化
mkdir my-pdf-app && cd my-pdf-app
npm init -y
npm install axios dotenv
# .env ファイル作成
echo "FUNBREW_API_KEY=your-api-key" > .env
echo "FUNBREW_API_URL=https://pdf.funbrew.cloud" >> .env
PDF生成の基本モジュール
// src/pdf-client.js
require('dotenv').config();
const axios = require('axios');
const client = axios.create({
baseURL: process.env.FUNBREW_API_URL || 'https://pdf.funbrew.cloud',
headers: {
Authorization: `Bearer ${process.env.FUNBREW_API_KEY}`,
Accept: 'application/json',
},
timeout: 30000,
});
/**
* APIに渡す options を組み立てる
* @param {object} options
* @param {'A3'|'A4'|'A5'|'Letter'|'Legal'} [options.pageSize] - 用紙サイズ(既定 A4)
* @param {'Portrait'|'Landscape'} [options.orientation] - 向き
* @param {{top?: number, right?: number, bottom?: number, left?: number}} [options.margin] - 余白(mm、0〜50)
* @param {'fast'|'quality'} [options.engine] - fast(wkhtmltopdf)/ quality(Chromium。Pro プラン以上)
*/
function buildOptions({ pageSize = 'A4', orientation, margin = {}, engine } = {}) {
const apiOptions = { 'page-size': pageSize };
if (orientation) apiOptions.orientation = orientation;
for (const side of ['top', 'right', 'bottom', 'left']) {
if (margin[side] !== undefined) apiOptions[`margin-${side}`] = margin[side];
}
if (engine) apiOptions.engine = engine;
return apiOptions;
}
/**
* HTMLからPDFを生成し、生成結果(JSON の data)を返す
* 応答は { success: true, data: { filename, download_url, public_url, file_size, expires_at, ... } }
*/
async function generatePdf(html, options = {}) {
const response = await client.post('/api/pdf/generate-from-html', {
html,
options: buildOptions(options),
});
return response.data.data;
}
/**
* HTMLからPDFを生成し、PDF本体(Buffer)を返す
* 1. 生成(応答はJSON)→ 2. download_url から同じAPIキーでPDF本体を取得
*/
async function htmlToPdf(html, options = {}) {
const { download_url } = await generatePdf(html, options);
const pdf = await client.get(download_url, { responseType: 'arraybuffer' });
return Buffer.from(pdf.data);
}
module.exports = { client, generatePdf, htmlToPdf };
生成APIはPDF本体ではなくJSONを返します。PDF本体は data.download_url(/api/pdf/download/{filename})を同じAPIキー付きで取得します。engine を省略すると、Free プランは fast、Pro 以上は会社の既定エンジン(未設定なら quality)になります。engine: 'quality' を Free で指定すると 403 です。ヘッダー/フッターのテンプレートを渡すオプションはありません(ページ番号は別API /api/pdf/page-numbers)。
APIドキュメントでオプションの完全仕様を確認できます。
パターン1: Express アプリへの組み込み
最も一般的なパターン。既存のExpressアプリにPDF生成エンドポイントを追加します。
npm install express
// src/app.js
require('dotenv').config();
const express = require('express');
const { generatePdf, htmlToPdf } = require('./pdf-client');
const app = express();
app.use(express.json());
// 利用者の入力をHTMLに埋め込む前にエスケープする
const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (ch) => (
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]
));
/**
* POST /invoices/pdf
* 請求書PDFを生成してレスポンスで返す
*/
app.post('/invoices/pdf', async (req, res) => {
const { customerName, amount, items = [] } = req.body;
if (!customerName || !amount) {
return res.status(400).json({ error: 'customerName と amount は必須です' });
}
try {
const html = buildInvoiceHtml({ customerName, amount, items });
const pdf = await htmlToPdf(html, {
pageSize: 'A4',
margin: { top: 25, bottom: 20, left: 20, right: 20 },
});
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="invoice-${Date.now()}.pdf"`,
'Content-Length': pdf.length,
});
res.send(pdf);
} catch (error) {
console.error('PDF生成エラー:', error.message);
res.status(500).json({ error: 'PDF生成に失敗しました', detail: error.message });
}
});
/**
* GET /reports/:type/pdf
* PDF本体は返さず、生成結果(ファイル名・サイズ・有効期限)だけを返す
*/
app.get('/reports/:type/pdf', async (req, res) => {
const { type } = req.params;
try {
const html = buildReportHtml(type);
const result = await generatePdf(html, {
pageSize: 'A4',
orientation: type === 'chart' ? 'Landscape' : 'Portrait',
});
// download_url の取得にはAPIキーが要るので、ブラウザにはそのまま渡さない。
// 利用者に配るなら PDF本体を取得して自前のストレージ(S3・GCS など)に保存するか、
// キー不要の public_url(/dl/<token>)を使う
res.json({
success: true,
filename: result.filename,
size: result.file_size,
expiresAt: result.expires_at,
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
function buildInvoiceHtml({ customerName, amount, items }) {
const tax = Math.floor(amount * 0.1);
const total = amount + tax;
const invoiceNumber = `INV-${Date.now()}`;
const date = new Date().toLocaleDateString('ja-JP');
return `<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Noto Sans JP', 'Hiragino Sans', sans-serif; color: #1e293b; padding: 40px; }
h1 { font-size: 28px; color: #2563eb; margin-bottom: 8px; }
.meta { color: #64748b; font-size: 13px; margin-bottom: 32px; }
table { width: 100%; border-collapse: collapse; margin: 24px 0; font-size: 13px; }
th { background: #f1f5f9; padding: 10px 12px; text-align: left; border-bottom: 2px solid #e2e8f0; }
td { padding: 10px 12px; border-bottom: 1px solid #e2e8f0; }
.total-section { text-align: right; margin-top: 16px; }
.total-row { font-size: 20px; font-weight: 700; color: #2563eb; }
body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
</style>
</head>
<body>
<h1>請求書</h1>
<div class="meta">
<p>請求番号: ${invoiceNumber}</p>
<p>発行日: ${date}</p>
<p>請求先: <strong>${escapeHtml(customerName)} 御中</strong></p>
</div>
<table>
<thead>
<tr><th>品目</th><th style="text-align:right">金額</th></tr>
</thead>
<tbody>
${items.length > 0
? items.map(item => `<tr><td>${escapeHtml(item.name)}</td><td style="text-align:right">¥${item.price.toLocaleString()}</td></tr>`).join('')
: `<tr><td>サービス利用料</td><td style="text-align:right">¥${amount.toLocaleString()}</td></tr>`
}
</tbody>
</table>
<div class="total-section">
<p>小計: ¥${amount.toLocaleString()}</p>
<p>消費税 (10%): ¥${tax.toLocaleString()}</p>
<p class="total-row">合計: ¥${total.toLocaleString()}</p>
</div>
</body>
</html>`;
}
function buildReportHtml(type) {
return `<!DOCTYPE html>
<html lang="ja">
<head><meta charset="UTF-8">
<style>body{font-family:sans-serif;padding:40px;}h1{color:#2563eb;}</style>
</head><body>
<h1>${type === 'weekly' ? '週次' : '月次'}レポート</h1>
<p>生成日時: ${new Date().toLocaleString('ja-JP')}</p>
</body></html>`;
}
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`サーバー起動: http://localhost:${PORT}`));
module.exports = app;
curlでのテスト
# 請求書PDF生成テスト
curl -X POST http://localhost:3000/invoices/pdf \
-H "Content-Type: application/json" \
-d '{"customerName":"株式会社サンプル","amount":100000}' \
-o invoice.pdf
# レポートPDF生成テスト
curl http://localhost:3000/reports/monthly/pdf
パターン2: AWS Lambda(サーバーレス)
Puppeteer を Lambda で動かすにはブラウザをパッケージに同梱する必要があり、パッケージが大きくなります。PDF APIを使えば、Lambda 関数はHTTPリクエストを送るだけで済みます。
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
// lambda/generate-pdf.mjs (ESM形式)
import { htmlToPdf } from './pdf-client.js';
import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
const s3 = new S3Client({ region: process.env.AWS_REGION || 'ap-northeast-1' });
const BUCKET = process.env.S3_BUCKET_NAME;
/**
* Lambda ハンドラ
* 直接呼び出し: { "type": "invoice", "customerId": "C001", "amount": 50000 }
* API Gateway 経由では同じJSONが event.body に文字列で入る
*/
export const handler = async (event) => {
const payload = typeof event.body === 'string' ? JSON.parse(event.body) : event;
const { type = 'invoice', customerId, amount } = payload;
try {
// PDF 生成
const html = buildHtml(type, { customerId, amount });
const pdfBuffer = await htmlToPdf(html, { pageSize: 'A4' });
// S3 に保存
const key = `pdfs/${type}/${customerId}-${Date.now()}.pdf`;
await s3.send(new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: pdfBuffer,
ContentType: 'application/pdf',
ServerSideEncryption: 'AES256',
}));
// ダウンロード用の署名付きURL(15分有効)を生成して返す
const downloadUrl = await getSignedUrl(
s3,
new GetObjectCommand({ Bucket: BUCKET, Key: key }),
{ expiresIn: 900 }
);
return {
statusCode: 200,
body: JSON.stringify({ success: true, key, downloadUrl }),
};
} catch (error) {
console.error('Lambda PDF生成エラー:', error);
return {
statusCode: 500,
body: JSON.stringify({ error: error.message }),
};
}
};
function buildHtml(type, data) {
return `<!DOCTYPE html>
<html lang="ja"><head><meta charset="UTF-8">
<style>body{font-family:'Noto Sans JP',sans-serif;padding:40px;}</style>
</head><body>
<h1>${type === 'invoice' ? '請求書' : 'レポート'}</h1>
<p>顧客ID: ${data.customerId}</p>
<p>金額: ¥${(data.amount || 0).toLocaleString()}</p>
<p>生成日時: ${new Date().toLocaleString('ja-JP')}</p>
</body></html>`;
}
# serverless.yml(Serverless Frameworkを使う場合。バケットは作成済みとする)
service: pdf-generator
provider:
name: aws
runtime: nodejs22.x
region: ap-northeast-1
environment:
FUNBREW_API_KEY: ${ssm:/pdf-generator/api-key}
FUNBREW_API_URL: https://pdf.funbrew.cloud
S3_BUCKET_NAME: my-pdf-bucket
iam:
role:
statements:
- Effect: Allow
Action: [s3:PutObject, s3:GetObject]
Resource: arn:aws:s3:::my-pdf-bucket/*
functions:
generatePdf:
handler: lambda/generate-pdf.handler
timeout: 30
events:
- http:
path: /pdf
method: post
cors: true
lambda/pdf-client.js には上の src/pdf-client.js を置きます(Node.js は CommonJS の module.exports を静的解析して、ESM から名前付きで import できるようにします。検出できない書き方のときは default import を使います)。API Gateway(REST API)の統合タイムアウトは既定で29秒なので、生成とダウンロードの合計がそれに収まることを実データで確かめてください。nodejs20.x は 2026年4月30日に非推奨になったため nodejs22.x にしています。
パターン3: Hono(Edge Runtime / Cloudflare Workers)
Honoは Cloudflare Workers・Deno・Bun・AWS Lambda・Node.js など多くの JavaScript ランタイムで動く軽量フレームワークです。
npm create hono@latest pdf-api-hono -- --template cloudflare-workers
cd pdf-api-hono && npm install
// src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
type Env = {
FUNBREW_API_KEY: string;
FUNBREW_API_URL: string;
};
const app = new Hono<{ Bindings: Env }>();
app.use('*', cors());
app.post('/pdf/invoice', async (c) => {
const { customerName, amount } = await c.req.json<{
customerName: string;
amount: number;
}>();
if (!customerName || !amount) {
return c.json({ error: 'customerName と amount は必須です' }, 400);
}
const html = buildInvoiceHtml(customerName, amount);
const auth = { Authorization: `Bearer ${c.env.FUNBREW_API_KEY}` };
// 1. 生成(応答はJSON)
const response = await fetch(`${c.env.FUNBREW_API_URL}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
html,
options: {
'page-size': 'A4',
'margin-top': 20,
'margin-bottom': 20,
'margin-left': 15,
'margin-right': 15,
},
}),
});
if (!response.ok) {
return c.json({ error: 'PDF生成失敗' }, 500);
}
const { data } = (await response.json()) as { data: { download_url: string } };
// 2. download_url から同じAPIキーでPDF本体を取得
const pdfResponse = await fetch(data.download_url, { headers: auth });
if (!pdfResponse.ok) {
return c.json({ error: 'PDF取得失敗' }, 500);
}
const pdfBuffer = await pdfResponse.arrayBuffer();
return new Response(pdfBuffer, {
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="invoice-${Date.now()}.pdf"`,
},
});
});
function buildInvoiceHtml(customerName: string, amount: number): string {
const tax = Math.floor(amount * 0.1);
return `<!DOCTYPE html>
<html lang="ja"><head><meta charset="UTF-8">
<style>body{font-family:sans-serif;padding:40px;color:#1e293b;}</style>
</head><body>
<h1 style="color:#2563eb">請求書</h1>
<p><strong>${escapeHtml(customerName)} 御中</strong></p>
<p>金額: ¥${amount.toLocaleString()}</p>
<p>消費税: ¥${tax.toLocaleString()}</p>
<p>合計: ¥${(amount + tax).toLocaleString()}</p>
</body></html>`;
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (ch) => (
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch] as string
));
}
export default app;
FUNBREW_API_URL は https://pdf.funbrew.cloud、APIキーは wrangler secret put FUNBREW_API_KEY で設定します。Workers 上で Puppeteer を使うには Cloudflare の Browser Rendering(@cloudflare/puppeteer)が別途要りますが、PDF APIなら fetch だけで済みます。サーバーレス環境でのPDF生成も参照してください。
パターン4: HTMLテンプレートファイルからの生成
実際の業務では、HTMLテンプレートをファイルとして管理し、変数を差し込んでPDFを生成するパターンが主流です。
npm install mustache # または handlebars, ejs など
// src/template-renderer.js
const fs = require('fs');
const path = require('path');
const Mustache = require('mustache');
/**
* テンプレートファイルにデータを差し込んでHTMLを生成する
*/
function renderTemplate(templateName, data) {
const templatePath = path.join(__dirname, '../templates', `${templateName}.html`);
const template = fs.readFileSync(templatePath, 'utf-8');
return Mustache.render(template, data);
}
module.exports = { renderTemplate };
<!-- templates/invoice.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
@page { size: A4; margin: 20mm 15mm; }
* { box-sizing: border-box; }
body {
font-family: 'Noto Sans JP', 'Hiragino Sans', sans-serif;
font-size: 12px;
color: #1e293b;
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.header { display: flex; justify-content: space-between; border-bottom: 3px solid #2563eb; padding-bottom: 16px; margin-bottom: 24px; }
.title { font-size: 28px; font-weight: 700; color: #2563eb; }
table { width: 100%; border-collapse: collapse; margin-top: 16px; }
th { background: #dbeafe; padding: 10px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #e2e8f0; }
.total { text-align: right; margin-top: 16px; font-size: 18px; font-weight: 700; }
</style>
</head>
<body>
<div class="header">
<div>
<div class="title">請求書</div>
<div>請求番号: {{invoiceNumber}}</div>
<div>発行日: {{issueDate}}</div>
</div>
<div style="text-align:right">
<strong>{{companyName}}</strong>
</div>
</div>
<p><strong>{{customerName}} 御中</strong></p>
<table>
<thead>
<tr><th>品目</th><th>数量</th><th>単価</th><th>小計</th></tr>
</thead>
<tbody>
{{#items}}
<tr>
<td>{{name}}</td>
<td style="text-align:right">{{quantity}}</td>
<td style="text-align:right">¥{{price}}</td>
<td style="text-align:right">¥{{subtotal}}</td>
</tr>
{{/items}}
</tbody>
</table>
<div class="total">
<div>小計: ¥{{subtotal}}</div>
<div>消費税 (10%): ¥{{tax}}</div>
<div style="font-size:22px; color:#2563eb">合計: ¥{{total}}</div>
</div>
</body>
</html>
// src/generate-invoice.js
const { renderTemplate } = require('./template-renderer');
const { htmlToPdf } = require('./pdf-client');
async function generateInvoicePdf(invoiceData) {
const {
customerName,
companyName = '株式会社FUNBREW',
items = [],
} = invoiceData;
// 合計計算
const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const tax = Math.floor(subtotal * 0.1);
const total = subtotal + tax;
const html = renderTemplate('invoice', {
invoiceNumber: `INV-${Date.now()}`,
issueDate: new Date().toLocaleDateString('ja-JP'),
customerName,
companyName,
items: items.map(item => ({
...item,
price: item.price.toLocaleString(),
subtotal: (item.price * item.quantity).toLocaleString(),
})),
subtotal: subtotal.toLocaleString(),
tax: tax.toLocaleString(),
total: total.toLocaleString(),
});
return htmlToPdf(html, {
engine: 'quality', // display: flex を使うので Chromium(Pro プラン以上)
pageSize: 'A4',
margin: { top: 20, bottom: 20, left: 15, right: 15 },
});
}
module.exports = { generateInvoicePdf };
Mustache の {{変数}} は既定でHTMLエスケープされるので、利用者の入力をそのまま渡せます。テンプレートのヘッダーは display: flex を使っているため quality エンジン向けです(fast エンジンの wkhtmltopdf は CSS2.1+一部のCSS3)。FUNBREW PDF 側にも変数を差し込むテンプレートAPI(/api/pdf/generate-from-template)がありますが、こちらは変数の置換だけでループは使えません。
PDFテンプレートエンジンガイドでより高度なテンプレート設計パターンを解説しています。
エラーハンドリングと本番環境対応
リトライとタイムアウト
// src/pdf-client.js — 本番対応版
const axiosRetry = require('axios-retry').default;
axiosRetry(client, {
retries: 3,
retryDelay: axiosRetry.exponentialDelay,
retryCondition: (error) => {
// ネットワークエラーと 5xx のみリトライ(4xx・429 はリトライしない)
return axiosRetry.isNetworkError(error)
|| (error.response?.status >= 500);
},
onRetry: (retryCount, error) => {
console.warn(`[PDF] リトライ ${retryCount}回目: ${error.message}`);
},
});
npm install axios-retry
生成リクエスト(POST)を 5xx でリトライすると、サーバー側で生成が済んでいた場合に二重に生成され、月間の生成数を余分に消費することがあります。リトライ回数は控えめにしてください。
ストリーミングレスポンス(大きなPDF向け)
// 生成後、PDF本体をストリームのままクライアントへ流す
const { client, generatePdf } = require('./pdf-client');
app.get('/reports/large/pdf', async (req, res) => {
try {
const html = buildLargeReportHtml();
const { download_url } = await generatePdf(html, { pageSize: 'A4' });
const pdf = await client.get(download_url, {
responseType: 'stream', // arraybuffer ではなく stream
});
res.set('Content-Type', 'application/pdf');
res.set('Content-Disposition', 'attachment; filename="report.pdf"');
pdf.data.pipe(res);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
PDF生成のパフォーマンス最適化
// src/pdf-queue.js — キューで並行数を制御
const { default: PQueue } = require('p-queue');
// 同時PDF生成を最大5件に制限
const queue = new PQueue({ concurrency: 5 });
async function generatePdfQueued(html, options) {
return queue.add(() => htmlToPdf(html, options));
}
// キューの状態を監視
queue.on('active', () => {
console.log(`[Queue] 実行中: ${queue.size}件待機, ${queue.pending}件処理中`);
});
module.exports = { generatePdfQueued };
npm install p-queue
p-queue は ESM 専用のパッケージです。上のように CommonJS から require() するには、require(esm) がフラグなしで使える Node.js 20.19 / 22.12 以降が要ります(それより古い場合は ESM で書くか import() を使います)。また FUNBREW PDF の毎分の上限は会社単位(APIキー間で共有)で、ダウンロードも1回と数えます。同時実行数を絞るだけでなく、429 の Retry-After に従って待ってください。
詳細な本番環境最適化はPDF API本番運用チェックリストを参照してください。
よくある質問
Node.js で最も簡単にPDFを生成するには?
FUNBREW PDF APIを使う方法なら、ブラウザをインストールせずに済みます。axios や組み込みの fetch で「生成(JSON が返る)→ download_url からPDF本体を取得」の2回のHTTPリクエストを書くだけで、HTMLをPDFに変換できます。サーバーレス環境からも呼び出せます。
PuppeteerでPDFを生成する場合の問題点は?
Puppeteerはローカル開発には便利ですが、本番環境では次の点に手間がかかります。(1) インストール時にダウンロードされる Chrome for Testing(Linux で約282MB)のデプロイ管理、(2) AWS LambdaやCloud Functionsでブラウザを同梱するためのパッケージの肥大化と起動時間、(3) ブラウザを起動するためのメモリ、(4) Dockerイメージサイズの増大。これらを避けたい場合にPDF APIが選択肢になります。
Node.js v18以降で変わった点は?
Node.js v18以降では組み込みのfetchがフラグなしで使えるため、axiosなどの外部HTTPライブラリなしでPDF APIを呼び出せます。
const baseUrl = process.env.FUNBREW_API_URL || 'https://pdf.funbrew.cloud';
const auth = { Authorization: `Bearer ${process.env.FUNBREW_API_KEY}` };
// 1. 生成(応答はJSON)
const response = await fetch(`${baseUrl}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ html, options: { 'page-size': 'A4' } }),
});
if (!response.ok) throw new Error(`PDF API error ${response.status}`);
const { data } = await response.json();
// 2. download_url から同じAPIキーでPDF本体を取得
const pdfResponse = await fetch(data.download_url, { headers: auth });
if (!pdfResponse.ok) throw new Error(`PDF download error ${pdfResponse.status}`);
const pdfBuffer = Buffer.from(await pdfResponse.arrayBuffer());
日本語PDFが文字化けする場合は?
まずHTMLに<meta charset="UTF-8">を書き、CSSのfont-familyに'Noto Sans JP'などの日本語フォントを指定してください。FUNBREW PDF の quality エンジンには Noto CJK フォントが入っていることを確かめる仕組みがありますが、使うエンジンで実際に出力して確認するのが確実です。詳しくは日本語フォントガイドを参照してください。
まとめ
Node.jsでのPDF生成パターンをまとめます。
| パターン | 実装 | 特徴 |
|---|---|---|
| Express API | POST /invoices/pdf エンドポイント |
同期レスポンス・即時ダウンロード |
| Lambda / サーバーレス | Event-driven + S3 | スケーラブル・コスト効率 |
| Edge Runtime(Hono) | Cloudflare Workers対応 | 低レイテンシ・グローバル配信 |
| テンプレートファイル | Mustache/Handlebars | 保守性・デザイナー対応 |
いずれのパターンでも、PDF生成の実体はFUNBREW PDF APIへの「生成」と「ダウンロード」の2回のHTTPリクエストです。プレイグラウンドでHTMLテンプレートをすぐに試せます。
関連記事
- PDF生成APIクイックスタート — Node.js/Python/PHPの基本的なAPIコール
- TypeScript × PDF API型安全ガイド — TypeScriptでの型安全な実装
- Next.js・Nuxt 3でPDF APIを使う完全ガイド — フレームワーク別の統合方法
- PDFサーバーレス・Lambda ガイド — AWS Lambda・Cloudflare Workersでの詳細実装
- PDF一括生成ガイド — 数百件のPDFを効率的に処理
- HTML→PDF CSS設計テクニック集(@page・改ページ・背景色の即効スニペット) — PDF専用CSSのベストプラクティス
- HTML→PDF変換のよくある問題と解決策 — レイアウト崩れ・タイムアウト・エンコーディングエラーの診断と修正
- PDF APIセキュリティガイド — APIキー管理とセキュリティ対策
- PDF API本番運用チェックリスト — 本番環境での安定運用
- PDFテンプレートエンジン入門 — 変数・ループ・条件分岐を使ったテンプレート設計
- APIリファレンス — エンドポイントの詳細仕様