Generate professional PDFs in Google Antigravity using React-PDF and Puppeteer for reports and invoices.
# PDF Generation Guide for Google Antigravity
Generate professional PDFs for invoices, reports, and documents in your Google Antigravity applications using React-PDF and Puppeteer approaches.
## React-PDF Server-Side Generation
```typescript
// lib/pdf/invoice.tsx
import React from "react";
import { Document, Page, Text, View, StyleSheet, Font, Image, renderToStream } from "@react-pdf/renderer";
Font.register({
family: "Inter",
fonts: [
{ src: "https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuLyfAZ9hiJ-Ek-_EeA.woff2" },
{ src: "https://fonts.gstatic.com/s/inter/v12/UcCO3FwrK3iLTeHuS_fvQtMwCp50KnMw2boKoduKmMEVuGKYAZ9hiJ-Ek-_EeA.woff2", fontWeight: "bold" },
],
});
const styles = StyleSheet.create({
page: { padding: 40, fontFamily: "Inter", fontSize: 10 },
header: { flexDirection: "row", justifyContent: "space-between", marginBottom: 40 },
logo: { width: 120, height: 40 },
title: { fontSize: 24, fontWeight: "bold", color: "#1a1a1a" },
invoiceInfo: { textAlign: "right" },
section: { marginBottom: 20 },
sectionTitle: { fontSize: 12, fontWeight: "bold", marginBottom: 8, color: "#333" },
table: { width: "100%" },
tableHeader: { flexDirection: "row", backgroundColor: "#f5f5f5", padding: 8, fontWeight: "bold" },
tableRow: { flexDirection: "row", borderBottomWidth: 1, borderBottomColor: "#eee", padding: 8 },
col1: { width: "50%" },
col2: { width: "20%", textAlign: "right" },
col3: { width: "15%", textAlign: "right" },
col4: { width: "15%", textAlign: "right" },
totals: { marginTop: 20, alignItems: "flex-end" },
totalRow: { flexDirection: "row", justifyContent: "flex-end", paddingVertical: 4 },
totalLabel: { width: 100 },
totalValue: { width: 80, textAlign: "right" },
grandTotal: { fontWeight: "bold", fontSize: 14, borderTopWidth: 2, borderTopColor: "#333", paddingTop: 8 },
footer: { position: "absolute", bottom: 40, left: 40, right: 40, textAlign: "center", color: "#888", fontSize: 8 },
});
interface InvoiceItem {
description: string;
quantity: number;
unitPrice: number;
}
interface InvoiceData {
invoiceNumber: string;
date: string;
dueDate: string;
customerName: string;
customerAddress: string;
items: InvoiceItem[];
taxRate: number;
}
export function InvoicePDF({ data }: { data: InvoiceData }) {
const subtotal = data.items.reduce((sum, item) => sum + item.quantity * item.unitPrice, 0);
const tax = subtotal * data.taxRate;
const total = subtotal + tax;
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.header}>
<View>
<Text style={styles.title}>INVOICE</Text>
<Text>Your Company Name</Text>
<Text>123 Business Street</Text>
</View>
<View style={styles.invoiceInfo}>
<Text>Invoice #{data.invoiceNumber}</Text>
<Text>Date: {data.date}</Text>
<Text>Due: {data.dueDate}</Text>
</View>
</View>
<View style={styles.section}>
<Text style={styles.sectionTitle}>Bill To:</Text>
<Text>{data.customerName}</Text>
<Text>{data.customerAddress}</Text>
</View>
<View style={styles.table}>
<View style={styles.tableHeader}>
<Text style={styles.col1}>Description</Text>
<Text style={styles.col2}>Qty</Text>
<Text style={styles.col3}>Price</Text>
<Text style={styles.col4}>Amount</Text>
</View>
{data.items.map((item, index) => (
<View key={index} style={styles.tableRow}>
<Text style={styles.col1}>{item.description}</Text>
<Text style={styles.col2}>{item.quantity}</Text>
<Text style={styles.col3}>${item.unitPrice.toFixed(2)}</Text>
<Text style={styles.col4}>${(item.quantity * item.unitPrice).toFixed(2)}</Text>
</View>
))}
</View>
<View style={styles.totals}>
<View style={styles.totalRow}>
<Text style={styles.totalLabel}>Subtotal:</Text>
<Text style={styles.totalValue}>${subtotal.toFixed(2)}</Text>
</View>
<View style={styles.totalRow}>
<Text style={styles.totalLabel}>Tax ({(data.taxRate * 100).toFixed(0)}%):</Text>
<Text style={styles.totalValue}>${tax.toFixed(2)}</Text>
</View>
<View style={[styles.totalRow, styles.grandTotal]}>
<Text style={styles.totalLabel}>Total:</Text>
<Text style={styles.totalValue}>${total.toFixed(2)}</Text>
</View>
</View>
<View style={styles.footer}>
<Text>Thank you for your business!</Text>
</View>
</Page>
</Document>
);
}
export async function generateInvoicePDF(data: InvoiceData): Promise<NodeJS.ReadableStream> {
return renderToStream(<InvoicePDF data={data} />);
}
```
## API Route for PDF Generation
```typescript
// app/api/invoice/[id]/pdf/route.ts
import { NextRequest, NextResponse } from "next/server";
import { generateInvoicePDF } from "@/lib/pdf/invoice";
import { createClient } from "@/lib/supabase/server";
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
const supabase = createClient();
const { data: invoice, error } = await supabase.from("invoices").select("*, items:invoice_items(*)").eq("id", params.id).single();
if (error || !invoice) {
return NextResponse.json({ error: "Invoice not found" }, { status: 404 });
}
const pdfStream = await generateInvoicePDF({
invoiceNumber: invoice.number,
date: invoice.created_at,
dueDate: invoice.due_date,
customerName: invoice.customer_name,
customerAddress: invoice.customer_address,
items: invoice.items,
taxRate: invoice.tax_rate,
});
return new NextResponse(pdfStream as unknown as BodyInit, {
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `attachment; filename="invoice-${invoice.number}.pdf"`,
},
});
}
```
## Puppeteer HTML-to-PDF
```typescript
// lib/pdf/puppeteer.ts
import puppeteer from "puppeteer";
export async function htmlToPdf(html: string, options?: { format?: "A4" | "Letter"; landscape?: boolean }): Promise<Buffer> {
const browser = await puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"] });
const page = await browser.newPage();
await page.setContent(html, { waitUntil: "networkidle0" });
const pdf = await page.pdf({
format: options?.format || "A4",
landscape: options?.landscape || false,
printBackground: true,
margin: { top: "20mm", right: "20mm", bottom: "20mm", left: "20mm" },
});
await browser.close();
return pdf;
}
```
## Best Practices
1. **Font Embedding**: Register custom fonts for consistent rendering across systems
2. **Streaming**: Use streaming responses for large PDFs to reduce memory usage
3. **Caching**: Cache generated PDFs when content does not change frequently
4. **Security**: Validate user permissions before generating sensitive documents
5. **Testing**: Test PDF generation across different data scenariosThis pdf prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their pdf implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For pdf projects, consider mentioning your framework version, coding style, and any specific libraries you're using.