HTML to PDF Troubleshooting: 12 Fixes for Blank PDF & Errors
You've built your HTML to PDF pipeline, but the output has garbled text, broken columns, tables spilling off the page, or images that simply don't appear. These problems are frustrating because the HTML looks perfect in the browser.
Common causes include a mismatch between PDF rendering engines and your HTML or CSS, unavailable fonts, and unreachable resources. This guide covers 12 common HTML to PDF problems — with Before/After code examples — when using FUNBREW PDF or any HTML to PDF tool. If you need the full picture of available conversion methods, start with the HTML to PDF Complete Guide.
Problem 1: Garbled Text and Missing Fonts
Symptoms
Text appears as boxes (□□□□), question marks, or is replaced by an unrelated character. CJK characters are especially susceptible.
Cause
The PDF rendering server doesn't have the required font installed, or CSS doesn't specify a fallback font chain that includes that language.
Fix
Before (generic font stack)
body {
font-family: sans-serif; /* No CJK font specified */
}
After (explicit font stack with CJK support)
body {
font-family: 'Noto Sans JP', 'Hiragino Sans', 'Yu Gothic', 'Meiryo', sans-serif;
}
code, pre {
font-family: 'Noto Sans Mono', 'Source Code Pro', monospace;
}
For self-hosted environments where you control the font files, embed the font as Base64:
@font-face {
font-family: 'IPAexGothic';
src: url('data:font/truetype;base64,AAEAAAA...') format('truetype');
}
body {
font-family: 'IPAexGothic', sans-serif;
}
If the rendering server has network access, Google Fonts works well:
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap');
body {
font-family: 'Noto Sans JP', sans-serif;
}
FUNBREW PDF has a verification mechanism for Noto Sans CJK JP families, but this does not guarantee every glyph. Specify
Noto Sans CJK JPin FUNBREW-specific CSS and inspect a PDF containing the actual text. For a comparison of font support across tools, see HTML to PDF API Comparison 2026.
FUNBREW PDF API example
These curl examples use jq to read the generation JSON, then download data.download_url with the same API key.
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<style>body { font-family: \"Noto Sans CJK JP\", sans-serif; }</style><p>日本語テキスト / Japanese text</p>",
"options": { "page-size": "A4" }
}' \
--output generation.json
download_url=$(jq -r '.data.download_url // empty' generation.json)
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output output.pdf
Problem 2: CSS Layout Breaks
Symptoms
Two-column layouts collapse to one column in the PDF. Flex containers behave unexpectedly. The PDF looks like a mobile layout even though the browser renders it correctly.
Cause
CSS support varies by engine and browser version, and media-query evaluation can differ from the screen context.
Fix
Before (modern CSS that may break in older engines)
.container {
display: flex;
gap: 24px; /* gap is unsupported in older engines */
}
.column {
width: 50%;
}
After (table-based layout for maximum compatibility)
.container {
display: table;
width: 100%;
border-spacing: 0;
}
.column {
display: table-cell;
width: 50%;
padding-right: 12px;
vertical-align: top;
}
.column:last-child {
padding-right: 0;
padding-left: 12px;
}
When using a Chromium-based engine, flexbox works fine if you lock in the width:
@media print {
.container {
display: flex;
width: 794px; /* A4 at 96dpi */
margin: 0;
padding: 0;
}
.column {
flex: 0 0 50%;
box-sizing: border-box;
}
}
Responsive designs often switch to a mobile layout at small viewport widths. Override this in print:
@media print {
.container {
max-width: none !important;
width: 100% !important;
}
.mobile-only {
display: none !important;
}
.desktop-only {
display: block !important;
}
}
Background colors are also frequently missing. Force them with:
* {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
For a detailed breakdown of CSS support per engine, see wkhtmltopdf vs Chromium.
Problem 3: Page Breaks in the Wrong Place
Symptoms
A table is split mid-row. A heading is left alone at the bottom of a page. You need a section to start on a new page.
Cause
Missing break-inside or break-before declarations, or missing legacy fallback properties for older engines.
Fix
Before (no page break control)
table { width: 100%; }
/* The engine decides where to break — often badly */
After (explicit page break control)
/* Prevent elements from splitting across pages */
table, figure, .card, .invoice-item {
break-inside: avoid;
page-break-inside: avoid; /* Fallback for older engines */
}
/* Never break right after a heading */
h1, h2, h3 {
break-after: avoid;
page-break-after: avoid;
}
/* Force a new page before specific sections */
.chapter, .page-break {
break-before: page;
page-break-before: always;
}
/* Prevent orphan and widow lines */
p {
orphans: 3; /* Minimum lines at bottom of page */
widows: 3; /* Minimum lines at top of page */
}
For multi-page tables, always repeat headers and prevent row splits:
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
tr {
break-inside: avoid;
page-break-inside: avoid;
}
For invoices, keep the summary block together on one page:
<div class="invoice-body">
<table class="line-items">
<thead>
<tr><th>Item</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr>
</thead>
<tbody>
<!-- line items -->
</tbody>
</table>
</div>
<!-- Keep the summary block together — no page break inside -->
<div class="invoice-summary" style="break-inside: avoid; page-break-inside: avoid;">
<table>
<tr><td>Subtotal</td><td>$1,000.00</td></tr>
<tr><td>Tax (10%)</td><td>$100.00</td></tr>
<tr><td><strong>Total</strong></td><td><strong>$1,100.00</strong></td></tr>
</table>
<p>Wire transfer: Bank of Example, Account #1234567</p>
</div>
For more @page rules and page break techniques, see CSS Page Breaks & @page Tips for HTML to PDF.
Problem 4: Images Don't Appear in the PDF
Symptoms
Images are blank, show a broken image icon, or display a completely different image. The issue doesn't exist in the browser.
Cause
Relative URLs or local file paths that the PDF rendering server cannot resolve.
Fix
Before (relative paths that the server can't reach)
<!-- Local file path: inaccessible from the rendering server -->
<img src="../images/logo.png" alt="Logo">
<!-- Relative URL: the server doesn't know the base URL -->
<img src="/images/logo.png" alt="Logo">
After (absolute URL)
<img src="https://example.com/images/logo.png" alt="Logo">
When network access isn't available, or you want to avoid extra HTTP requests, embed images as Base64:
import base64
def image_to_base64(path: str) -> str:
with open(path, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
logo_b64 = image_to_base64('logo.png')
html = f'<img src="data:image/png;base64,{logo_b64}" alt="Logo" width="200">'
const fs = require('fs');
function imageToBase64(path) {
return fs.readFileSync(path).toString('base64');
}
const logoB64 = imageToBase64('./logo.png');
const html = `<img src="data:image/png;base64,${logoB64}" alt="Logo" width="200">`;
For SVGs, embed the markup directly — no encoding needed:
<svg width="200" height="60" xmlns="http://www.w3.org/2000/svg">
<text x="10" y="40" font-size="32" font-family="Arial">FUNBREW</text>
</svg>
FUNBREW PDF API example with image
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<img src=\"https://your-cdn.example.com/logo.png\" alt=\"Logo\"><p>Content below logo</p>",
"options": { "page-size": "A4" }
}' \
--output generation.json
download_url=$(jq -r '.data.download_url // empty' generation.json)
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output output.pdf
Problem 5: Tables Overflow or Get Cut Off
Symptoms
A wide table extends beyond the right edge of the page. Content on the right side of the table is missing from the PDF.
Cause
PDF has no concept of horizontal scrolling. overflow: auto has no effect. If a table is wider than the page, the content is simply clipped.
Fix
Before (scroll works in browser, but PDF clips content)
.table-wrapper {
overflow-x: auto; /* No effect in PDF */
}
table {
min-width: 900px; /* Wider than A4 (~794px at 96dpi) */
}
After (fit the table to the page)
table {
width: 100%;
table-layout: fixed; /* Distribute column widths evenly */
word-break: break-all; /* Wrap long text within cells */
}
@media print {
table {
font-size: 8pt; /* Reduce font size for dense tables */
}
td, th {
padding: 4px 6px;
}
}
For tables with many columns, switch to landscape orientation:
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<table>...</table>",
"options": {
"page-size": "A4",
"orientation": "Landscape"
}
}' \
--output generation.json
download_url=$(jq -r '.data.download_url // empty' generation.json)
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output output.pdf
Hide supplementary columns in PDF output:
@media print {
.col-notes,
.col-actions {
display: none;
}
}
For a deeper look at fitting wide tables, controlling column widths, and repeating headers, see the HTML to PDF table layout guide.
Problem 6: External CSS or Styles Are Not Applied
Symptoms
The PDF ignores font styles, colors, or layout rules that look correct in the browser. External stylesheet links don't appear to load.
Cause
The PDF rendering server cannot reach the relative URL of the external CSS file, or the file is behind authentication.
Fix
Before (external CSS reference)
<!-- Rendering server may not be able to reach this -->
<link rel="stylesheet" href="/assets/style.css">
After (inline CSS)
<style>
body {
font-family: 'Noto Sans JP', 'Arial', sans-serif;
font-size: 11pt;
line-height: 1.7;
color: #1a202c;
margin: 0;
padding: 0;
}
h1 { font-size: 18pt; font-weight: 700; margin-bottom: 12pt; }
h2 { font-size: 14pt; font-weight: 700; margin-bottom: 8pt; }
.highlight { background: #fef9c3; padding: 2px 4px; }
</style>
Read and inline CSS server-side before sending to the API:
def build_html_with_styles(html_content: str, css_path: str) -> str:
with open(css_path, 'r', encoding='utf-8') as f:
css = f.read()
return f'<style>{css}</style>{html_content}'
html = build_html_with_styles('<h1>Report</h1><p>Content</p>', 'style.css')
const fs = require('fs');
function buildHtmlWithStyles(htmlContent, cssPath) {
const css = fs.readFileSync(cssPath, 'utf-8');
return `<style>${css}</style>${htmlContent}`;
}
const html = buildHtmlWithStyles('<h1>Report</h1>', './style.css');
Problem 7: Dynamic Content Missing (JavaScript-Rendered Elements)
Symptoms
Charts, graphs, or dynamically rendered UI components appear blank or empty in the PDF.
Cause
The PDF engine captures the page before JavaScript finishes rendering the content.
Fix
Before (JavaScript hasn't finished when PDF is captured)
{
"html": "<canvas id='chart'></canvas><script>renderChart();</script>",
"options": {}
}
After (use an approach with explicit rendering control)
The FUNBREW PDF API has no option to wait for document.title or an arbitrary JavaScript expression. Render charts as server-side images and embed them, or use explicit waits such as Gotenberg's waitForExpression or Puppeteer's waiting APIs in a self-hosted setup.
Chart.js supports disabling animation:
const chart = new Chart(ctx, {
type: 'bar',
data: { /* ... */ },
options: {
animation: false, // Disable animations
responsive: false, // Fix dimensions
plugins: {
legend: { display: true }
}
}
});
To avoid depending on an API wait setting, generate the chart as a server-side image. Also check image quality and text selection in the resulting PDF:
import matplotlib.pyplot as plt
import io, base64
def chart_to_base64(data: list) -> str:
fig, ax = plt.subplots(figsize=(6, 4))
ax.bar(range(len(data)), data)
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi=150, bbox_inches='tight')
buf.seek(0)
return base64.b64encode(buf.read()).decode()
chart_b64 = chart_to_base64([10, 25, 40, 35, 55])
html = f'<img src="data:image/png;base64,{chart_b64}" alt="Revenue Chart">'
Problem 8: Headers and Footers Not Appearing
Symptoms
You've set up @page margins and added header/footer elements, but the PDF renders them incorrectly — overlapping content, cut off, or completely missing.
Cause
Header and footer rendering differs across PDF engines. Chrome 131 added @page margin boxes and page counters, but older engines differ. FUNBREW quality also falls back to fast when Gotenberg is not configured.
Fix
Before (CSS header that requires target-engine verification)
@page {
@top-center { content: "Company Name"; }
@bottom-right { content: "Page " counter(page); }
}
After (repeat fixed-position elements on printed pages)
<style>
@page {
margin: 25mm 15mm 25mm 15mm; /* Leave space for header/footer */
}
.page-header {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 15mm;
text-align: center;
font-size: 9pt;
color: #718096;
border-bottom: 0.5pt solid #e2e8f0;
padding-bottom: 2mm;
}
.page-footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 15mm;
text-align: center;
font-size: 8pt;
color: #a0aec0;
}
</style>
<div class="page-header">Company Name — Confidential</div>
<div class="page-footer">Generated by FUNBREW PDF</div>
<div class="content">
<!-- Main content here -->
</div>
Fixed-position elements repeat at the same position on printed pages, but they need enough margin to avoid overlapping content. For page numbers, use @page margin boxes in Chrome 131+ and verify the target environment. FUNBREW has no displayHeaderFooter, headerTemplate, or footerTemplate API options.
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<style>@page { margin: 25mm 15mm; @bottom-center { content: counter(page); } }</style><h1>Report</h1><p>Content...</p>",
"options": {
"page-size": "A4",
"margin-top": 25,
"margin-bottom": 25,
"engine": "quality"
}
}' \
--output generation.json
download_url=$(jq -r '.data.download_url // empty' generation.json)
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output output.pdf
Problem 9: PDF Generation Timeout or Slow Performance
Symptoms
The API request takes over 30 seconds and eventually times out, or the PDF is slow to generate even for simple pages.
Cause
Large images, external resource loading (fonts, stylesheets, images from slow CDNs), complex JavaScript execution, or excessively large HTML payloads.
Fix
Reduce image sizes before embedding
from PIL import Image
import io, base64
def optimize_image(path: str, max_width: int = 800, quality: int = 80) -> str:
"""Resize and compress an image before Base64 embedding."""
with Image.open(path) as source:
img = source.convert('RGB')
if img.width > max_width:
ratio = max_width / img.width
img = img.resize((max_width, int(img.height * ratio)), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=quality, optimize=True)
return base64.b64encode(buf.getvalue()).decode()
Inline all external resources
import re, requests, base64
def inline_external_resources(html: str) -> str:
"""Replace external image URLs with Base64-encoded inline data."""
def replace_src(match):
url = match.group(1)
if url.startswith("data:"):
return match.group(0)
try:
resp = requests.get(url, timeout=10)
resp.raise_for_status()
content_type = resp.headers.get("content-type", "").split(";")[0]
if not content_type.startswith("image/"):
raise ValueError(f"Non-image Content-Type: {content_type}")
b64 = base64.b64encode(resp.content).decode()
return f'src="data:{content_type};base64,{b64}"'
except Exception:
return match.group(0)
return re.sub(r'src="(https?://[^"]+)"', replace_src, html)
Pass only trusted, allowlisted image domains to this inlining helper; do not let users make the server fetch arbitrary URLs.
Set appropriate timeouts and reduce payload size
const fs = require('fs');
const apiKey = process.env.FUNBREW_PDF_API_KEY;
// Send HTML unchanged so whitespace in pre and script elements is preserved
const response = await axios.post(
'https://pdf.funbrew.cloud/api/pdf/generate-from-html',
{ html, options: { 'page-size': 'A4' } },
{
timeout: 60000,
headers: { 'Authorization': `Bearer ${apiKey}` },
}
);
const pdfResponse = await axios.get(response.data.data.download_url, {
timeout: 60000,
responseType: 'arraybuffer',
headers: { 'Authorization': `Bearer ${apiKey}` },
});
fs.writeFileSync('output.pdf', Buffer.from(pdfResponse.data));
A longer client timeout does not extend server-side limits. Measure resource reachability, image size, and HTML size separately, and distinguish generation from download timing.
Problem 10: PDF File Size Too Large
Symptoms
A single-page PDF is several megabytes. Batch-generated PDFs consume excessive storage. Email attachments exceed size limits.
Cause
High-resolution embedded images (especially uncompressed PNGs), embedded fonts, or redundant CSS.
Fix
Compress images before embedding
Use JPEG instead of PNG for photographs, and SVG for logos and icons:
# Consider JPEG for photos; compare actual quality and size with PNG
img.save(buf, format="JPEG", quality=75, optimize=True)
# Use SVG for logos and simple graphics (no Base64 needed)
logo_svg = '<svg width="200" height="60">...</svg>'
Separate display size from image data size
CSS max-width and image-rendering control presentation; they do not reduce the source image's embedded byte count. Resize and compress the actual image before calling the API, then inspect both PDF appearance and file size.
Post-process: compress the generated PDF
import subprocess
def compress_pdf(input_path: str, output_path: str):
"""Use Ghostscript to compress a PDF file."""
subprocess.run([
"gs", "-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
"-dPDFSETTINGS=/ebook", # Medium-resolution preset
"-dNOPAUSE", "-dBATCH",
f"-sOutputFile={output_path}",
input_path,
], check=True)
# PDFSETTINGS presets alter the input; compare quality and size on actual files
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
async function compressPdf(inputPath, outputPath) {
await execFileAsync('gs', [
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.4',
'-dPDFSETTINGS=/ebook',
'-dNOPAUSE',
'-dBATCH',
`-sOutputFile=${outputPath}`,
inputPath,
]);
}
Debugging Workflow
Use this step-by-step approach to isolate the cause of any PDF issue.
Step 1: Check browser print preview
Most problems reproduce in the browser's print preview, which is the fastest way to diagnose them.
- Open the HTML in Chrome
- Press
Ctrl+Shift+P(Mac:Cmd+Shift+P) to open the command palette - Type "Emulate CSS media type" → select "print"
- Open Print Preview with
Ctrl+P
If the issue appears here, it's a CSS problem. If print preview looks correct, suspect a rendering engine issue.
Step 2: Test in the Playground
Paste your HTML into FUNBREW PDF's Playground for instant PDF output — no API key required.
Step 3: Compare engines
FUNBREW PDF offers fast (wkhtmltopdf) and quality. The latter uses Chromium on paid plans when Gotenberg is configured and falls back to fast otherwise.
generate_pdf() {
local engine=$1
local output=$2
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d "{\"html\": \"<p>Test</p>\", \"options\": {\"engine\": \"$engine\"}}" \
--output "generation-$engine.json"
local download_url
download_url=$(jq -r '.data.download_url // empty' "generation-$engine.json")
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output "$output"
}
generate_pdf fast test-fast.pdf
generate_pdf quality test-quality.pdf
If outputs differ, investigate CSS and font compatibility between the engines. See wkhtmltopdf vs Chromium for specifics.
Step 4: Create a minimal reproduction
Strip the HTML down to the smallest snippet that still reproduces the problem.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
/* Only the relevant styles */
body { font-family: 'Noto Sans JP', sans-serif; }
</style>
</head>
<body>
<!-- Minimal element that triggers the issue -->
<p>Test: Hello World / 日本語</p>
</body>
</html>
Step 5: Check error responses
import requests
headers = {"Authorization": "Bearer your-api-key"}
response = requests.post(
"https://pdf.funbrew.cloud/api/pdf/generate-from-html",
headers=headers,
json={"html": html_content, "options": {}},
timeout=60,
)
if not response.ok:
print(f"HTTP {response.status_code}")
print(response.text)
else:
result = response.json()
pdf_response = requests.get(
result["data"]["download_url"], headers=headers, timeout=60
)
pdf_response.raise_for_status()
with open("output.pdf", "wb") as f:
f.write(pdf_response.content)
For a comprehensive guide to error handling and retry logic, see the PDF API Error Handling Guide.
Problem 11: Table Headers Not Repeating Across Pages
Symptoms
A multi-page table shows the header row only on the first page. From page two onward, readers can't tell which column is which.
Cause
Even with thead { display: table-header-group; }, document structure and engine behavior can produce different results. Check these areas:
- The scope of break avoidance: Remove
break-inside: avoidfrom the whole table and ancestors, then apply it to rows or small groups. - Complex structures: Compare a minimal example without nested tables,
rowspan, or a direct Flexbox/Grid parent. - The actual engine: FUNBREW
qualityuses Chromium on paid plans with Gotenberg configured and falls back tofastotherwise.
Fix
Before (header doesn't repeat)
/* break-inside: avoid on the whole table blocks header repetition */
table {
break-inside: avoid;
page-break-inside: avoid;
}
<!-- Table inside a flex container — header won't repeat -->
<div style="display: flex;">
<table>
<thead><tr><th>Item</th><th>Amount</th></tr></thead>
<tbody><!-- many rows --></tbody>
</table>
</div>
After (correct header repetition)
/* Remove break-inside from the table element — control it per row instead */
table {
width: 100%;
border-collapse: collapse;
}
/* The key rule for repeating headers */
thead {
display: table-header-group;
}
tfoot {
display: table-footer-group;
}
/* Control page breaks at the row level, not the table level */
tr {
break-inside: avoid;
page-break-inside: avoid;
}
<!-- Place the table in a block context, not inside flex/grid -->
<div style="display: block;">
<table>
<thead>
<tr>
<th style="background: #f0f4f8; font-weight: bold;">Item</th>
<th style="background: #f0f4f8; font-weight: bold;">Qty</th>
<th style="background: #f0f4f8; font-weight: bold;">Unit Price</th>
<th style="background: #f0f4f8; font-weight: bold;">Total</th>
</tr>
</thead>
<tbody>
<!-- rows -->
</tbody>
</table>
</div>
FUNBREW PDF API example with repeating table header
curl --fail-with-body -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<!DOCTYPE html><html><head><style>table { width: 100%; border-collapse: collapse; } thead { display: table-header-group; } th, td { border: 1px solid #e2e8f0; padding: 8px 12px; } tr { break-inside: avoid; page-break-inside: avoid; }</style></head><body><table><thead><tr><th>Item</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr></thead><tbody><!-- Render line items on the server --></tbody></table></body></html>",
"options": {
"page-size": "A4",
"engine": "quality"
}
}' \
--output generation.json
download_url=$(jq -r '.data.download_url // empty' generation.json)
test -n "$download_url"
curl --fail-with-body "$download_url" \
-H "Authorization: Bearer YOUR_API_KEY" \
--output table-report.pdf
The CSS specification permits print user agents to repeat
<tfoot>footer rows on every spanned page. To show a total only once after the final items, use a separate<div class="summary" style="break-inside: avoid;">after the table and verify its position in the PDF.
Checklist when header repetition doesn't work
| Check | How to verify |
|---|---|
thead has display: table-header-group |
Inspect in browser DevTools |
No break-inside: avoid on the <table> element |
Search CSS for the rule |
| Table is not a direct child of a flex/grid container | Review HTML structure |
Engine is set to quality (Chromium) |
Check engine in your API request |
| No nested tables | Flatten the HTML structure |
For more @page rules and page break recipes, see the @page & page-break CSS guide.
Problem 12: Chromium Errors — Target closed, net::ERR_FAILED, Protocol error
You're running Puppeteer or Playwright directly and the call fails with one of these errors:
Error: Protocol error (Page.printToPDF): Target closed.
Error: net::ERR_FAILED at https://example.com/...
Error: Page crashed!
TimeoutError: Waiting for selector "..." failed: timeout 30000ms exceeded
These are some of the most reported errors when self-hosting headless Chromium, and the root cause is rarely a single line of code.
Cause
- Resource pressure — Insufficient memory or shared memory can terminate Chromium. Requirements vary by page and concurrency.
- Early cleanup — Closing a page or browser before
page.pdf()finishes can fail the render. - Resource access failures — Unreachable CSS, JavaScript, or image hosts can produce errors such as
net::ERR_FAILED. - Version differences — Puppeteer guarantees compatibility with its bundled browser. Verify output when using a different Chromium.
- Missing cleanup — Close the browser on error paths too. Monitor actual resource use rather than choosing a fixed recycling interval.
Fix (Self-hosted Chromium)
async function renderPdf(url) {
const browser = await puppeteer.launch({
headless: true,
args: ['--disable-dev-shm-usage'],
});
try {
const page = await browser.newPage();
await page.goto(url, { waitUntil: 'networkidle0', timeout: 60000 });
await page.emulateMediaType('print');
return await page.pdf({ format: 'A4', printBackground: true });
} finally {
await browser.close();
}
}
Align container sandbox settings with the official Docker image and your security policy. Monitor memory, shared memory, and file descriptors under actual load.
docker stats your-pdf-service
Fix (PDF API)
With FUNBREW PDF, you do not manage a local Chromium process. Your application still needs to handle plan features, rate limits, external-resource reachability, and error responses.
const fs = require('fs');
const apiKey = process.env.FUNBREW_PDF_API_KEY;
const authorization = `Bearer ${apiKey}`;
const res = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-url', {
method: 'POST',
headers: { 'Authorization': authorization, 'Content-Type': 'application/json' },
body: JSON.stringify({
url,
options: { 'page-size': 'A4', engine: 'quality' },
}),
});
const result = await res.json();
if (!res.ok) {
throw new Error(`PDF generation failed: ${res.status} ${JSON.stringify(result)}`);
}
const pdfResponse = await fetch(result.data.download_url, {
headers: { 'Authorization': authorization },
});
if (!pdfResponse.ok) {
throw new Error(`PDF download failed: ${pdfResponse.status}`);
}
fs.writeFileSync('output.pdf', Buffer.from(await pdfResponse.arrayBuffer()));
See the PDF API error handling guide for retry strategies and the Puppeteer migration guide for a full self-host → API comparison. If you're on Playwright, the complete Playwright PDF generation guide covers page.pdf()-specific error handling and implementation patterns.
Quick Reference
| Problem | Common Cause | Fix |
|---|---|---|
| Garbled text (tofu boxes) | Missing font on rendering server | Specify full font stack; use pre-installed fonts |
| Layout breaks | CSS incompatibility, wrong viewport | Table layout; @media print with fixed widths |
| Wrong page breaks | Missing break-inside |
break-inside: avoid + orphans/widows |
| Images missing | Relative URLs or inaccessible paths | Use absolute URLs or Base64 inline embedding |
| Table overflow | Width exceeds page | table-layout: fixed + word-break: break-all |
| Styles not applied | External CSS unreachable | Inline all CSS before sending to the API |
| Dynamic content missing | JS not finished before capture | Server-side image generation |
| Headers/footers missing | Engine-specific @page support |
Verify Chrome 131+ margin boxes or position: fixed in the output |
| Slow generation/timeout | Large images, external resources | Optimize images, check reachability, measure generation and download |
| File size too large | Uncompressed images, embedded fonts | JPEG instead of PNG, SVG for icons, Ghostscript post-processing |
Summary
Start by checking font availability, engine-specific CSS behavior, resource access, and cleanup around browser calls.
- Garbled text: Specify a font covering the actual text; use
Noto Sans CJK JPfor FUNBREW and inspect the PDF - Layout issues: Check CSS reachability and define print layouts in
@media print - Page breaks: Use
break-inside: avoidandorphans/widows, including checks for oversized elements - Missing resources: Use reachable absolute URLs or Base64 embedding and verify the output
- Headers/footers: Use Chrome 131+
@pagemargin boxes orposition: fixed - Slow generation: Optimize images and resources; measure generation and download separately
- Large file size: Consider JPEG for photos and SVG for graphics; compare quality after Ghostscript processing
- Debugging: Browser print preview first, then Playground, then minimal reproduction
For deep dives into specific areas, see CSS Tips for HTML to PDF and the wkhtmltopdf vs Chromium comparison. Start testing in the Playground — it's the fastest way to confirm whether your HTML produces the PDF you expect.
Related
- HTML to PDF Complete Guide 2026 — Overview of all conversion methods
- CSS for PDF: @page, Page Breaks & Print Tips — Page breaks, margins, and font design in depth
- wkhtmltopdf vs Chromium — Engine-specific CSS compatibility
- PDF API Error Handling Guide — Error handling and retry strategies
- PDF API Quickstart by Language — Node.js, Python, PHP code examples
- HTML to PDF API Comparison 2026 — Feature and pricing comparison across services
- API Documentation — Full FUNBREW PDF option reference
- Playground — Test your HTML and get PDF output instantly
- Use Cases — Invoices, reports, certificates, and more
- Pricing — Free plan to production plans