Claude Code से PDF Generation: Playwright invoices, reports और print CSS
Claude Code से PDF बनाएं: Playwright, print CSS, Hindi/Japanese fonts, invoices, reports और visual checks.
किसी web app में “Download PDF” button जोड़ना आसान लगता है, लेकिन production document अलग चीज है। Invoice में सही amount, tax, margin, table alignment और due date चाहिए। Monthly report में text, table, screenshot, chart और page break संभालने पड़ते हैं। Certificate में नाम, date, ID, logo और print layout भरोसेमंद दिखना चाहिए।
इस guide में सबसे practical तरीका लिया गया है: HTML-to-PDF with browser rendering। Document HTML में बनता है, paper size और margin print CSS से control होते हैं, फिर Chromium उसे render करके PDF export करता है। Playwright और Puppeteer दोनों इस pattern के लिए अच्छे हैं। Claude Code जल्दी implementation दे सकता है, लेकिन prompt में साफ लिखना होगा कि पूरा document canvas image नहीं बनाना है, fonts wait करने हैं, background print करना है और screenshot verification रखना है।
Official docs को source of truth रखें: Playwright page.pdf, Puppeteer PDF generation और PDFOptions, MDN @page और printing CSS, तथा Claude Code overview. Related reading: spreadsheet automation, Playwright testing, और testing strategies.
HTML-to-PDF क्यों बेहतर शुरुआती रास्ता है
PDF बनाने के तीन common तरीके हैं। पहला, jsPDF जैसे library से coordinates पर text और lines draw करना। Simple label के लिए ठीक है, लेकिन invoice में हर बदलाव x और y value बदलने जैसा हो जाता है। दूसरा, पूरा page या canvas image बनाकर PDF में डालना। यह जल्दी सुंदर दिख सकता है, पर text search, copy, zoom, accessibility और file size में कमजोर है।
तीसरा तरीका HTML-to-PDF है। Table table ही रहता है, heading heading ही रहती है, और @page से A4 size व margin control होते हैं। PDF export से पहले वही HTML browser में खुल सकता है, इसलिए screenshot comparison और visual regression आसान हो जाते हैं। Claude Code भी normal HTML, CSS, Node script और Playwright test edit करता है, obscure coordinate math नहीं।
flowchart TD
A["Business data"] --> B["HTML template"]
B --> C["Print CSS और @page"]
C --> D["Chromium render"]
D --> E["PDF file"]
C --> F["Screenshot comparison"]
F --> G["Review evidence"]
Real use cases
पहला use case invoice है। इसमें seller, buyer, line items, tax, total, due date और invoice number चाहिए। असली risk styling नहीं, बल्कि गलत rounding, missing tax, invisible background, या total block का next page में टूट जाना है।
दूसरा use case monthly report है। SEO, ads, SaaS usage और sales reports में summary, charts, screenshots और recommendations आते हैं। यहाँ page flow important है। Heading page के bottom में अकेली न रहे और chart अपनी explanation से अलग न हो।
तीसरा use case certificate है। Name, course, date, certificate ID, logo और QR code अक्सर एक page पर फिट होते हैं। पूरा certificate image बनाने के बजाय important text HTML में रखें, और image सिर्फ logo, signature या QR के लिए रखें।
चौथा use case audit report है। Permissions, deployments, approvals और incident notes बाद में trace करने पड़ते हैं। Footer में generated date, environment, app version और source data ID रखना practical है।
Claude Code prompt
PDF generation implement करें।
Direction:
- HTML template को Playwright Chromium से render करके PDF export करें।
- पूरे document को single canvas image न बनाएं।
- A4 portrait, 14mm margins, visible backgrounds और print CSS use करें।
- Hindi, English और Japanese के लिए robust font stack रखें।
- Structure invoice, report और certificate में reuse हो सके।
Implementation:
- scripts/create-invoice-pdf.mjs add करें।
- Sample data से out/invoice-IN-2026-0602.pdf generate करें।
- Money Intl.NumberFormat से format करें।
- User input HTML escape करें।
- page.pdf में printBackground और preferCSSPageSize use करें।
Verification:
- Run command document करें।
- Print HTML screenshot comparison के लायक रखें।
- Fonts, page breaks, backgrounds और total check करें।
Copy-paste runnable code
npm init -y
npm pkg set type=module
npm i -D playwright
npx playwright install chromium
mkdir scripts out
node scripts/create-invoice-pdf.mjs
import { chromium } from "playwright";
import { mkdir } from "node:fs/promises";
import { dirname, resolve } from "node:path";
const outputPath = resolve("out/invoice-IN-2026-0602.pdf");
const money = new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" });
const invoice = {
number: "IN-2026-0602",
buyer: "Sample Digital Pvt. Ltd.",
seller: "Masa Design Lab",
issuedAt: "2026-06-02",
items: [
{ name: "PDF template design", quantity: 1, unitPrice: 65000 },
{ name: "Playwright generation script", quantity: 1, unitPrice: 95000 },
{ name: "Print CSS and font verification", quantity: 1, unitPrice: 45000 },
],
};
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
})[char]);
}
function renderHtml(data) {
const subtotal = data.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0);
const tax = Math.round(subtotal * 0.18);
const rows = data.items.map((item) => `<tr>
<td>${escapeHtml(item.name)}</td>
<td class="num">${item.quantity}</td>
<td class="num">${money.format(item.unitPrice)}</td>
<td class="num">${money.format(item.quantity * item.unitPrice)}</td>
</tr>`).join("");
return `<!doctype html><html lang="en-IN"><head><meta charset="utf-8">
<style>
@page { size: A4; margin: 14mm; }
body { font-family: "Noto Sans Devanagari", "Noto Sans", Arial, sans-serif; color: #202124; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
header { display: flex; justify-content: space-between; border-bottom: 3px solid #1f5eff; padding-bottom: 14px; }
h1 { margin: 0; font-size: 28px; }
table { width: 100%; border-collapse: collapse; margin-top: 24px; }
th { background: #eef3ff; text-align: left; }
th, td { border-bottom: 1px solid #d7dce5; padding: 10px 8px; }
.num { text-align: right; white-space: nowrap; }
.total { margin-left: auto; width: 260px; margin-top: 20px; font-size: 18px; font-weight: 700; }
.avoid-break { break-inside: avoid; page-break-inside: avoid; }
</style></head><body>
<header><h1>Invoice</h1><div>No: ${escapeHtml(data.number)}<br>Date: ${escapeHtml(data.issuedAt)}</div></header>
<p><strong>Buyer:</strong> ${escapeHtml(data.buyer)}</p>
<p><strong>Seller:</strong> ${escapeHtml(data.seller)}</p>
<table><thead><tr><th>Item</th><th class="num">Qty</th><th class="num">Unit</th><th class="num">Amount</th></tr></thead><tbody>${rows}</tbody></table>
<div class="total avoid-break">Total: ${money.format(subtotal + tax)}</div>
</body></html>`;
}
await mkdir(dirname(outputPath), { recursive: true });
const browser = await chromium.launch();
try {
const page = await browser.newPage();
await page.setContent(renderHtml(invoice), { waitUntil: "networkidle" });
await page.evaluate(() => document.fonts.ready);
await page.emulateMedia({ media: "print" });
await page.pdf({ path: outputPath, printBackground: true, preferCSSPageSize: true, margin: { top: "0", right: "0", bottom: "0", left: "0" } });
console.log(`Created ${outputPath}`);
} finally {
await browser.close();
}
Failure cases और checks
Common failures हैं: whole PDF को image बनाना, printBackground भूलना, CI server पर fonts missing होना, external logo load होने से पहले export करना, user text escape न करना, और long note से total block टूटना। Claude Code को बोलें कि पहले failure reproduce करे, फिर smallest useful patch दे।
Verification में सिर्फ “PDF file बना” काफी नहीं है। Total calculation का unit test रखें। Print route खोलकर page.emulateMedia({ media: "print" }) लगाएं और Playwright screenshot comparison रखें। Short invoice, long invoice, missing logo और multilingual text के साथ manual review करें।
Monetization CTA और verified result
PDF generation monetizable topic है क्योंकि यह invoices, reports, certificates, checklists और client deliverables से जुड़ता है। शुरुआत free Claude Code resources से करें, repeatable templates के लिए ClaudeCodeLab products देखें, और team workflow में PDF generation, review और Playwright जोड़ना हो तो training और consultation देखें।
इस article का workflow local Node.js, Playwright Chromium और sample invoice data से verify किया गया। सबसे useful habit page.pdf call नहीं, बल्कि print HTML को testable surface मानना था। Masa के practical work में font loading, missing backgrounds और page-break drift syntax error से ज्यादा बार problem बनते हैं।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.