Python PDF生成完全ガイド|ReportLab・WeasyPrint・API比較と実装例
「PythonでPDFを生成したい」という要件は、請求書・レポート・証明書・帳票など、あらゆるWebアプリやデータパイプラインで発生します。Pythonにはライブラリが豊富にある一方、それぞれに得意・不得意があります。
この記事では、Pythonプロジェクトでよく使われる6つのアプローチを実際に動くコード例とともに比較し、ユースケース別の選び方を解説します。FUNBREW PDF APIを使う方法を中心に、Django・FastAPI・Flask連携、バッチ処理まで幅広くカバーします。
PythonでのPDF生成:6つのアプローチ比較
まず主要な手法を一覧で比較します。
| アプローチ | HTMLサポート | CSS精度 | 依存関係 | サーバーレス | おすすめ用途 |
|---|---|---|---|---|---|
| FUNBREW PDF API | 完全 | 高(quality=Chromium。Pro以上)/中(fast=wkhtmltopdf) | requestsのみ |
対応 | 本番環境・SaaS・複雑レイアウト |
| ReportLab | なし | — | 中 | 対応 | 数値・グラフ・データレポート |
| WeasyPrint | 完全 | 中〜高 | 大(Pango等のシステムライブラリ) | 困難 | HTMLメール→PDF・中規模アプリ |
| xhtml2pdf | HTML5(CSSは一部) | 低〜中 | 中(Pure Python・ReportLab) | 対応 | 小規模・シンプルなレイアウト |
| pdfkit(wkhtmltopdf) | 完全 | 中 | wkhtmltopdfバイナリ | 困難 | 既存wkhtmltopdf環境の維持 |
| Playwright for Python | 完全 | 高(Chromium) | Chromiumバイナリ | 困難 | ローカル・テスト自動化兼用 |
複雑なHTMLレイアウト(グラフ・表・日本語フォント)を含む業務PDFには PDF API が最も適しています。PDF APIとライブラリの比較で詳しく解説しています。
1. FUNBREW PDF API(推奨)
インストールと基本設定
pip install requests python-dotenv
# pdf_client.py
import os
import requests
from dotenv import load_dotenv
load_dotenv()
FUNBREW_API_KEY = os.environ["FUNBREW_API_KEY"]
# ホストだけを定数にし、パスは呼び出し側でフルに書く
FUNBREW_BASE_URL = os.getenv("FUNBREW_BASE_URL", "https://pdf.funbrew.cloud")
AUTH_HEADERS = {"Authorization": f"Bearer {FUNBREW_API_KEY}"}
def html_to_pdf(
html: str,
engine: str | None = None,
page_size: str = "A4",
orientation: str = "Portrait",
margin_mm: dict | None = None,
) -> bytes:
"""
HTML文字列をPDFに変換し、PDFのバイナリを返す(生成→ダウンロードの2リクエスト)。
Args:
html: PDF化するHTML文字列
engine: "quality"(Chromium。Proプラン以上)または "fast"(wkhtmltopdf)。
省略するとプランに応じて選ばれる
page_size: 用紙サイズ("A3", "A4", "A5", "Letter", "Legal")
orientation: "Portrait"(縦)または "Landscape"(横)
margin_mm: 余白(top/right/bottom/left を mm の数値で。0〜50)
Returns:
PDFのバイナリデータ(bytes)
"""
if margin_mm is None:
margin_mm = {"top": 20, "right": 15, "bottom": 20, "left": 15}
options = {"page-size": page_size, "orientation": orientation}
for side, value in margin_mm.items():
options[f"margin-{side}"] = value
if engine:
options["engine"] = engine
# 1. 生成: 応答は JSON で、data.download_url にダウンロード先が入る
response = requests.post(
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
headers=AUTH_HEADERS,
json={"html": html, "options": options},
timeout=60,
)
response.raise_for_status()
download_url = response.json()["data"]["download_url"]
# 2. ダウンロード: 同じ API キーで PDF 本体を取得する
pdf_response = requests.get(download_url, headers=AUTH_HEADERS, timeout=60)
pdf_response.raise_for_status()
return pdf_response.content
生成APIの応答はPDFそのものではなくJSON(success・data.download_url など)です。PDF本体は download_url(/api/pdf/download/{filename})から同じAPIキーで取得します。options で指定できるのは page-size・orientation・margin-top/right/bottom/left(mm、0〜50)・engine で、quality(Chromium)はProプラン以上で使えます(Freeで指定すると403)。
APIドキュメントでオプションの完全仕様を確認できます。
基本的な使い方
# generate_basic.py
from pdf_client import html_to_pdf
html = """<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
body { font-family: 'Noto Sans CJK JP', sans-serif; padding: 40px; color: #1e293b; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>Hello, PDF!</h1>
<p>PythonからFUNBREW PDF APIでPDFを生成しました。</p>
</body>
</html>"""
pdf_bytes = html_to_pdf(html)
with open("output.pdf", "wb") as f:
f.write(pdf_bytes)
print(f"PDF生成完了: {len(pdf_bytes):,} bytes")
請求書PDFの実用例
# invoice_generator.py
from datetime import date
from html import escape
from pdf_client import html_to_pdf
def build_invoice_html(
customer_name: str,
amount: int,
items: list[dict] | None = None,
company_name: str = "株式会社FUNBREW",
) -> str:
tax = int(amount * 0.1)
total = amount + tax
invoice_number = f"INV-{date.today().strftime('%Y%m%d')}-001"
issue_date = date.today().strftime("%Y年%m月%d日")
if not items:
items = [{"name": "サービス利用料", "quantity": 1, "price": amount}]
rows = "".join(
f"<tr><td>{escape(item['name'])}</td>"
f"<td style='text-align:right'>{item['quantity']}</td>"
f"<td style='text-align:right'>¥{item['price']:,}</td>"
f"<td style='text-align:right'>¥{item['price'] * item['quantity']:,}</td></tr>"
for item in items
)
return f"""<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
@page {{ size: A4; margin: 20mm 15mm; }}
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{
font-family: 'Noto Sans CJK 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; }}
.total-amount {{ font-size: 22px; font-weight: 700; color: #2563eb; }}
</style>
</head>
<body>
<div class="header">
<div>
<div class="title">請求書</div>
<div>請求番号: {invoice_number}</div>
<div>発行日: {issue_date}</div>
</div>
<div style="text-align:right"><strong>{escape(company_name)}</strong></div>
</div>
<p><strong>{escape(customer_name)} 御中</strong></p>
<table>
<thead>
<tr><th>品目</th><th>数量</th><th>単価</th><th>小計</th></tr>
</thead>
<tbody>{rows}</tbody>
</table>
<div class="total">
<p>小計: ¥{amount:,}</p>
<p>消費税 (10%): ¥{tax:,}</p>
<p class="total-amount">合計: ¥{total:,}</p>
</div>
</body>
</html>"""
def generate_invoice_pdf(customer_name: str, amount: int, items=None) -> bytes:
html = build_invoice_html(customer_name, amount, items)
return html_to_pdf(html, page_size="A4")
if __name__ == "__main__":
pdf = generate_invoice_pdf(
customer_name="株式会社サンプル",
amount=150_000,
items=[
{"name": "Webシステム開発", "quantity": 1, "price": 120_000},
{"name": "保守サポート(月額)", "quantity": 3, "price": 10_000},
],
)
with open("invoice.pdf", "wb") as f:
f.write(pdf)
print(f"請求書PDF生成: {len(pdf):,} bytes")
エラーハンドリングとリトライ
再試行してよいのは、毎分のリクエスト上限による429(Retry-After ヘッダー付き)と5xx・通信エラーです。月間の生成件数上限による429には Retry-After が無く、翌月まで解消しないので再試行しません。422(入力不備)や403(プランにない機能)も再試行しても結果は変わりません。
# pdf_client_production.py
import time
import requests
from pdf_client import FUNBREW_BASE_URL, AUTH_HEADERS
RETRYABLE_STATUS = {500, 502, 503, 504}
def post_with_retry(url: str, payload: dict, max_attempts: int = 3) -> requests.Response:
"""毎分上限の429(Retry-Afterあり)と5xx・通信エラーだけを再試行する"""
for attempt in range(1, max_attempts + 1):
try:
response = requests.post(url, headers=AUTH_HEADERS, json=payload, timeout=60)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
time.sleep(2 ** (attempt - 1)) # 1秒, 2秒
continue
last_attempt = attempt == max_attempts
if response.status_code == 429 and "Retry-After" in response.headers and not last_attempt:
time.sleep(int(response.headers["Retry-After"]))
continue
if response.status_code in RETRYABLE_STATUS and not last_attempt:
time.sleep(2 ** (attempt - 1))
continue
# 422・403・月間上限の429などはここで例外にして止める
response.raise_for_status()
return response
raise RuntimeError("unreachable")
def html_to_pdf_with_retry(html: str, options: dict | None = None) -> bytes:
response = post_with_retry(
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
{"html": html, "options": options or {"page-size": "A4"}},
)
download_url = response.json()["data"]["download_url"]
pdf_response = requests.get(download_url, headers=AUTH_HEADERS, timeout=60)
pdf_response.raise_for_status()
return pdf_response.content
5xxやタイムアウトのあとに再送すると、サーバー側では生成が済んでいてPDFが2件でき、両方が月間件数に数えられることがあります。再試行の回数は小さく保ってください。
2. ReportLab
インストール
pip install reportlab
基本的な使い方
# reportlab_basic.py
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Table, TableStyle, Spacer
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from io import BytesIO
# 日本語を使う場合は TrueType フォント(.ttf / .ttc)を登録する
# pdfmetrics.registerFont(TTFont("JPFont", "/path/to/your-japanese-font.ttf"))
def generate_report_pdf(title: str, data: list[list]) -> bytes:
"""
ReportLabで表形式レポートPDFを生成する。
日本語を使う場合はフォント登録が必要。
"""
buffer = BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
topMargin=20 * mm,
bottomMargin=20 * mm,
leftMargin=15 * mm,
rightMargin=15 * mm,
)
styles = getSampleStyleSheet()
elements = []
# タイトル
elements.append(Paragraph(title, styles["Title"]))
elements.append(Spacer(1, 12))
# テーブル
table = Table(data, colWidths=[80 * mm, 40 * mm, 40 * mm])
table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#2563eb")),
("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
("FONTSIZE", (0, 0), (-1, 0), 11),
("ALIGN", (1, 0), (-1, -1), "RIGHT"),
("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#f1f5f9")]),
("GRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#e2e8f0")),
("TOPPADDING", (0, 0), (-1, -1), 8),
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
]))
elements.append(table)
doc.build(elements)
return buffer.getvalue()
if __name__ == "__main__":
data = [
["商品名", "数量", "金額"],
["Product A", "10", "¥50,000"],
["Product B", "5", "¥30,000"],
["Product C", "20", "¥80,000"],
]
pdf = generate_report_pdf("売上レポート 2026年4月", data)
with open("report_reportlab.pdf", "wb") as f:
f.write(pdf)
print(f"ReportLab PDF: {len(pdf):,} bytes")
ReportLabの特徴:
- HTMLなしでプログラム的にPDFを組み立てる低水準API
- 日本語は、TrueTypeフォント(
.ttf/.ttc)をTTFontで登録するか、組み込みのCIDフォント(UnicodeCIDFont("HeiseiKakuGo-W5")など)を使う - グラフ描画(
reportlab.graphics)が得意 - 複雑なHTMLレイアウトの再現は困難
3. WeasyPrint
インストール
# macOS(Homebrew。公式ドキュメントの推奨)
brew install weasyprint
# Debian 11以降(pipで入れる場合に必要なパッケージ)
sudo apt install python3-pip libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz-subset0
pip install weasyprint
基本的な使い方
# weasyprint_basic.py
from weasyprint import HTML, CSS
from io import BytesIO
def html_to_pdf_weasyprint(html: str, base_url: str | None = None) -> bytes:
"""WeasyPrintでHTMLをPDFに変換する"""
buffer = BytesIO()
HTML(string=html, base_url=base_url).write_pdf(
buffer,
stylesheets=[CSS(string="@page { size: A4; margin: 20mm 15mm; }")],
)
return buffer.getvalue()
html = """<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
body { font-family: sans-serif; padding: 20px; }
h1 { color: #2563eb; border-bottom: 2px solid #2563eb; padding-bottom: 8px; }
table { width: 100%; border-collapse: collapse; margin-top: 16px; }
th { background: #dbeafe; padding: 8px; text-align: left; }
td { padding: 8px; border-bottom: 1px solid #e2e8f0; }
</style>
</head>
<body>
<h1>WeasyPrint デモ</h1>
<table>
<thead><tr><th>項目</th><th>値</th></tr></thead>
<tbody>
<tr><td>ライブラリ</td><td>WeasyPrint</td></tr>
<tr><td>テキスト描画</td><td>Pango</td></tr>
<tr><td>日本語対応</td><td>システムフォント使用</td></tr>
</tbody>
</table>
</body>
</html>"""
pdf = html_to_pdf_weasyprint(html)
with open("output_weasyprint.pdf", "wb") as f:
f.write(pdf)
print(f"WeasyPrint PDF: {len(pdf):,} bytes")
WeasyPrintの特徴:
- CSS Paged Media(
@page・ページの余白ボックス・ページカウンタ)に対応。FlexboxとGridは「単純なケースで動く」水準 - WebKitやGeckoのようなブラウザエンジンではないため、JavaScriptで描画する内容はPDFに出ない
- Pangoなどのシステムライブラリに依存し、Dockerではパッケージの追加が要る
- 日本語はシステムにインストールされたフォントに依存(環境によってフォントが変わる)
4. xhtml2pdf
インストール
pip install xhtml2pdf
基本的な使い方
# xhtml2pdf_basic.py
from io import BytesIO
from xhtml2pdf import pisa
def html_to_pdf_xhtml2pdf(html: str) -> bytes:
"""xhtml2pdfでHTMLをPDFに変換する"""
buffer = BytesIO()
result = pisa.CreatePDF(html, dest=buffer)
if result.err:
raise RuntimeError(f"xhtml2pdf変換エラー: {result.err}")
return buffer.getvalue()
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
@page { size: A4; margin: 20mm; }
/* 日本語を出すには @font-face で日本語フォント(TTF/OTF)を指定する */
body { font-family: sans-serif; font-size: 12px; }
h1 { color: #2563eb; }
</style>
</head>
<body>
<h1>xhtml2pdf サンプル</h1>
<p>シンプルなPDFを手軽に生成できます。</p>
</body>
</html>"""
pdf = html_to_pdf_xhtml2pdf(html)
with open("output_xhtml2pdf.pdf", "wb") as f:
f.write(pdf)
print(f"xhtml2pdf PDF: {len(pdf):,} bytes")
xhtml2pdfの特徴:
- Pure Python(ReportLabの上に実装)で、ブラウザや外部バイナリが不要
- 0.2.28ではFlexbox・CSS変数(
var())に対応。CSS Gridは対応機能の一覧に無い - シンプルなレイアウトには十分だが、ブラウザと同じ見た目になるとは限らないので出力を確認する
- 日本語は
@font-faceでTrueType/OpenTypeフォントを指定する
5. pdfkit(wkhtmltopdf)
インストール
# wkhtmltopdfバイナリが別途必要
# macOS: brew install wkhtmltopdf
# Ubuntu: sudo apt-get install wkhtmltopdf
pip install pdfkit
基本的な使い方
# pdfkit_basic.py
import pdfkit
options = {
"page-size": "A4",
"margin-top": "20mm",
"margin-bottom": "20mm",
"margin-left": "15mm",
"margin-right": "15mm",
"encoding": "UTF-8",
"enable-local-file-access": "",
}
# HTML文字列からPDF生成
html = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>body{font-family:sans-serif;padding:40px;}</style>
</head>
<body>
<h1 style="color:#2563eb">pdfkit サンプル</h1>
<p>wkhtmltopdfを使ってPDFを生成します。</p>
</body>
</html>"""
# ファイルに保存
pdfkit.from_string(html, "output_pdfkit.pdf", options=options)
# バイナリとして取得
pdf_bytes = pdfkit.from_string(html, False, options=options)
print(f"pdfkit PDF: {len(pdf_bytes):,} bytes")
# URLからPDF生成
# pdfkit.from_url("https://example.com", "output_url.pdf")
pdfkitの特徴:
- wkhtmltopdfバイナリが必須(サーバーへのインストールが必要)
- 描画エンジンは古いQtWebKitで、最新のCSSには追従していない
- wkhtmltopdfのGitHubリポジトリは2023年1月にアーカイブされ、更新が止まっている
- 既存のwkhtmltopdf環境を維持する場合に有用
6. Playwright for Python
インストール
pip install playwright
playwright install chromium
基本的な使い方
# playwright_basic.py
import asyncio
from playwright.async_api import async_playwright
async def html_to_pdf_playwright(html: str, output_path: str = "output.pdf") -> bytes:
"""Playwright for PythonでHTMLをPDFに変換する(非同期)"""
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html, wait_until="networkidle")
pdf_bytes = await page.pdf(
format="A4",
margin={"top": "20mm", "bottom": "20mm", "left": "15mm", "right": "15mm"},
print_background=True,
)
await browser.close()
return pdf_bytes
async def main():
html = """<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<style>
body { font-family: 'Noto Sans JP', sans-serif; padding: 40px; }
h1 { color: #2563eb; }
.chart-placeholder {
width: 400px; height: 200px; background: #dbeafe;
display: flex; align-items: center; justify-content: center;
border-radius: 8px; font-size: 14px; color: #1e40af;
}
</style>
</head>
<body>
<h1>Playwright PDF デモ</h1>
<p>JavaScriptのレンダリング結果を含むPDFを生成できます。</p>
<div class="chart-placeholder">グラフエリア(JS描画)</div>
</body>
</html>"""
pdf = await html_to_pdf_playwright(html)
with open("output_playwright.pdf", "wb") as f:
f.write(pdf)
print(f"Playwright PDF: {len(pdf):,} bytes")
asyncio.run(main())
Playwright for Pythonの特徴:
- Playwrightが取得したChromiumで描画し、JavaScriptの実行結果も含めてPDFを生成できる
playwright install chromiumでブラウザがダウンロードされる(公式ドキュメントは「数百MBのディスク」と案内)- ローカル開発・テスト自動化と組み合わせる場合に特に有効
- 本番環境ではFUNBREW PDF APIに移行するとインフラが軽くなる
ユースケース別の選び方
請求書・契約書(複雑なレイアウト、日本語あり)
推奨: FUNBREW PDF API
# ✅ 既存のHTMLとCSSをそのまま使う(quality は Pro プラン以上)
pdf = html_to_pdf(invoice_html, engine="quality")
HTMLとCSSで既にデザインされた帳票テンプレートがある場合、生成とダウンロードの2回のHTTPリクエストでPDFを得られます。Django・FastAPIでのPDF API連携も参照してください。
データ分析レポート(グラフ・表のみ)
推奨: ReportLab
# ✅ matplotlibのグラフをReportLabに埋め込む
# (elements は前節の generate_report_pdf() 内のリスト)
from reportlab.lib.units import mm
from reportlab.platypus import Image as RLImage
import matplotlib.pyplot as plt
from io import BytesIO
# matplotlibでグラフを生成
fig, ax = plt.subplots(figsize=(5, 3))
ax.bar(["Q1", "Q2", "Q3", "Q4"], [120, 145, 132, 178])
ax.set_title("四半期売上")
img_buffer = BytesIO()
fig.savefig(img_buffer, format="png", dpi=150, bbox_inches="tight")
img_buffer.seek(0)
plt.close(fig)
# ReportLabに埋め込む
chart_img = RLImage(img_buffer, width=130*mm, height=78*mm)
elements.append(chart_img)
大量バッチ生成(数百〜数千件)
推奨: FUNBREW PDF API + 非同期並列処理
# batch_pdf.py
import asyncio
import aiohttp
from pdf_client import FUNBREW_BASE_URL, AUTH_HEADERS
from invoice_generator import build_invoice_html
async def request_json_or_bytes(session: aiohttp.ClientSession, method: str, url: str, **kwargs):
"""毎分上限の429はRetry-After秒待って再試行(最大3回)。POSTはJSON、GETはバイト列を返す"""
for attempt in range(3):
async with session.request(method, url, headers=AUTH_HEADERS, **kwargs) as resp:
if resp.status == 429 and "Retry-After" in resp.headers and attempt < 2:
wait_seconds = int(resp.headers["Retry-After"])
else:
resp.raise_for_status()
return await (resp.json() if method == "POST" else resp.read())
await asyncio.sleep(wait_seconds)
async def html_to_pdf_async(
session: aiohttp.ClientSession,
html: str,
semaphore: asyncio.Semaphore,
) -> bytes:
async with semaphore:
result = await request_json_or_bytes(
session,
"POST",
f"{FUNBREW_BASE_URL}/api/pdf/generate-from-html",
json={"html": html, "options": {"page-size": "A4"}},
)
return await request_json_or_bytes(session, "GET", result["data"]["download_url"])
async def generate_pdfs_batch(html_list: list[str], concurrency: int = 5) -> list[bytes]:
"""複数のHTMLを並列でPDF変換する"""
semaphore = asyncio.Semaphore(concurrency) # 同時5件に制限
timeout = aiohttp.ClientTimeout(total=120)
async with aiohttp.ClientSession(timeout=timeout) as session:
tasks = [html_to_pdf_async(session, html, semaphore) for html in html_list]
results = await asyncio.gather(*tasks, return_exceptions=True)
# エラーを除外して成功分だけ返す
pdfs = []
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"[警告] {i}番目のPDF生成に失敗: {result}")
else:
pdfs.append(result)
return pdfs
async def main():
# 10件の請求書を並列生成
html_list = [
build_invoice_html(f"顧客{i:03d}", 100_000 + i * 5_000)
for i in range(1, 11)
]
pdfs = await generate_pdfs_batch(html_list, concurrency=5)
print(f"{len(pdfs)}件のPDFを生成しました")
if __name__ == "__main__":
asyncio.run(main())
並列数を上げても速くなるとは限りません。毎分のリクエスト上限は会社(APIキー共通)単位でプランごとに決まっており(Free 10・Pro 120・Business 300)、生成とダウンロードの両方が1回ずつ数えられます。月間の生成件数(Free 30件など)も超えられません。1リクエストで複数件をまとめて送る /api/pdf/batch も全プラン(Freeを含む)で使えます。
詳細なバッチ処理のパターンはPDF一括生成ガイドを参照してください。
FastAPI・Django での組み込み
# FastAPI エンドポイント例
import requests
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel
from pdf_client import html_to_pdf
from invoice_generator import build_invoice_html
app = FastAPI()
class InvoiceRequest(BaseModel):
customer_name: str
amount: int
items: list[dict] | None = None
# requests は同期処理なので async def ではなく def にする(FastAPIがスレッドプールで実行する)
@app.post("/invoices/pdf")
def create_invoice_pdf(req: InvoiceRequest):
html = build_invoice_html(req.customer_name, req.amount, req.items)
try:
pdf_bytes = html_to_pdf(html, page_size="A4")
except requests.RequestException as e:
raise HTTPException(status_code=502, detail="PDF generation failed") from e
return Response(
content=pdf_bytes,
media_type="application/pdf",
headers={"Content-Disposition": 'attachment; filename="invoice.pdf"'},
)
Django・Flask・FastAPIでの詳細な実装はDjango・FastAPI・FlaskでのPDF API統合ガイドで解説しています。
ライブラリ別 詳細比較
CSSサポート比較
FUNBREW PDF APIの列は quality(Chromium)エンジンの場合です。fast(wkhtmltopdf)はpdfkitと同じエンジンです。
| CSS機能 | FUNBREW PDF API(quality) | WeasyPrint | xhtml2pdf(0.2.28) | pdfkit |
|---|---|---|---|---|
| Flexbox | ✅ | △(単純なケース) | ✅ | 要確認 |
| CSS Grid | ✅ | △(単純なケース) | 記載なし | 要確認 |
| CSS変数 | ✅ | ✅ | ✅ | 要確認 |
@page ルール |
✅ | ✅ | ✅(サイズ・余白) | 要確認 |
@font-face |
✅ | ✅ | ✅ | 要確認 |
print-color-adjust |
✅(-webkit- 接頭辞版も併記する) |
記載なし | 記載なし | 要確認 |
wkhtmltopdf(pdfkit)は古いQtWebKitで描画するため、使うCSSごとに実際の出力で確かめてください。どのライブラリでも、表は公式ドキュメントの記載をもとにした目安です。
依存関係の比較
# FUNBREW PDF API
pip install requests
# WeasyPrint(Pango・HarfBuzz などのシステムライブラリと日本語フォントが別途必要)
pip install weasyprint
# pdfkit(wkhtmltopdf のバイナリが別途必要)
pip install pdfkit
# Playwright(ブラウザを別途ダウンロード。公式ドキュメントは「数百MBのディスク」と案内)
pip install playwright
playwright install chromium
よくある質問
PythonでPDFを最も簡単に生成するには?
FUNBREW PDF APIを使う方法が最も簡単です。pip install requestsだけで始められ、HTMLを送って返ってきた download_url からPDFを受け取るだけです。quality(Chromium)エンジンを使えば、複雑なHTMLのレイアウトやCSSもブラウザで描画した形で変換できます。外部バイナリのインストールが不要なため、Dockerイメージも軽量に保てます。
WeasyPrintをDockerで使うには?
Pango・HarfBuzzなどのシステムライブラリと、日本語を出すならフォントをインストールする必要があります。Debian bookwormベースのイメージなら次のとおりです(WeasyPrint 70.0で日本語のPDFが出力できることを確認しました):
FROM python:3.12-slim-bookworm
RUN apt-get update && apt-get install -y --no-install-recommends \
libpango-1.0-0 \
libpangoft2-1.0-0 \
libharfbuzz-subset0 \
fonts-noto-cjk \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir weasyprint
ただし、イメージサイズが増えるため、本番環境ではPDF APIへの切り替えも検討してください。
Pythonで日本語PDFが文字化けする場合は?
HTMLに<meta charset="UTF-8">を記述し、CSSで日本語フォントを指定してください。FUNBREW PDFのquality(Chromium)エンジンの環境にはNoto CJKフォントが入っているので、font-family: 'Noto Sans CJK JP', sans-serif;と指定できます。fastエンジンではフォントの見え方が変わることがあるため、生成したPDFで確認してください。詳しくは日本語フォントガイドを参照してください。
ReportLabで日本語を使うには?
方法は2つあります。組み込みのCIDフォント(日本語は HeiseiMin-W3・HeiseiKakuGo-W5)を使うか、TrueTypeフォント(.ttf/.ttc)を登録します:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfbase.ttfonts import TTFont
# 1. 組み込みのCIDフォント
pdfmetrics.registerFont(UnicodeCIDFont("HeiseiKakuGo-W5"))
# 以降 fontName="HeiseiKakuGo-W5" で使用可能
# 2. 手元の TrueType フォントを登録する
pdfmetrics.registerFont(TTFont("JPFont", "/path/to/your-japanese-font.ttf"))
# 以降 fontName="JPFont" で使用可能
pdfkitとWeasyPrint、どちらを選ぶべきか?
新規プロジェクトでは WeasyPrint を推奨します。pdfkitが依存するwkhtmltopdfはGitHubリポジトリが2023年1月にアーカイブされて更新が止まっており、描画エンジンも古いQtWebKitです。ブラウザと同じ描画(Chromium)が必要なら FUNBREW PDF API のqualityエンジン(Proプラン以上)も選択肢です。
まとめ
PythonでのPDF生成手法をユースケース別にまとめます。
| ユースケース | 推奨手法 | 理由 |
|---|---|---|
| 請求書・証明書・帳票(HTMLデザインあり) | FUNBREW PDF API | Chromium描画(quality)・サーバーにブラウザ不要 |
| データ分析レポート(グラフ中心) | ReportLab | matplotlib連携・プログラム生成 |
| 既存HTMLアーカイブのPDF変換 | WeasyPrint | CSS Paged Media対応 |
| シンプルな帳票(社内ツール) | xhtml2pdf | バイナリ不要・手軽 |
| E2Eテストとの兼用 | Playwright | ブラウザ制御も同時にできる |
| 大量バッチ生成・本番SaaS | FUNBREW PDF API | 描画サーバーの運用が不要(プランの月間件数・毎分上限の範囲で) |
どのケースでも、まずプレイグラウンドでHTMLテンプレートを確認することをおすすめします。APIドキュメントでエンドポイントの詳細仕様も参照してください。
関連記事
- PDF生成APIクイックスタート — Python/Node.js/PHPの基本的なAPIコール
- Django・FastAPI・FlaskでのPDF API統合ガイド — Webフレームワーク別の実装パターン
- Node.js PDF生成完全ガイド — Node.js版の姉妹記事
- PDF一括生成ガイド — 数百件のPDFを効率的に処理
- HTML→PDF CSS設計テクニック集(@page・改ページ・背景色の即効スニペット) — PDF専用CSSのベストプラクティス
- HTML→PDF変換のよくある問題と解決策 — レイアウト崩れ・タイムアウト・エンコーディングエラーの診断と修正
- 日本語フォントガイド — 日本語PDF生成の完全対応
- Puppeteer移行ガイド — Playwrightからの移行を検討する場合
- PDF APIとライブラリの比較 — APIとOSSライブラリの詳細な比較
- PDF API本番運用チェックリスト — 本番環境での安定運用
- APIリファレンス — エンドポイントの詳細仕様