Claude Code for fpdf2: Python PDF Generation — Claude Skills 360 Blog
Blog / AI / Claude Code for fpdf2: Python PDF Generation
AI

Claude Code for fpdf2: Python PDF Generation

Published: April 25, 2028
Read time: 5 min read
By: Claude Skills 360

fpdf2 generates PDF documents in pure Python. pip install fpdf2. Basic: from fpdf import FPDF. pdf = FPDF(); pdf.add_page(); pdf.set_font("Helvetica", size=12). pdf.cell(0, 10, "Hello World"). pdf.output("out.pdf"). Font: pdf.set_font("Helvetica", "B", 14) — B=bold I=italic U=underline. pdf.set_font("Times", size=11). pdf.set_font("Courier"). Cell: pdf.cell(w, h, text, border=1, align="C", fill=True). w=0 — full remaining width. Multi-cell: pdf.multi_cell(0, 8, long_text) — wraps at width. Line break: pdf.ln(5). pdf.ln() — default height. Colors: pdf.set_fill_color(200, 200, 200). pdf.set_text_color(255, 0, 0). pdf.set_draw_color(0, 0, 0). Image: pdf.image("logo.png", x=10, y=10, w=50). pdf.image(io.BytesIO(data), ...). Position: pdf.set_x(10), pdf.set_y(50), pdf.set_xy(10, 50). Size: pdf.get_string_width(text). pdf.epw — effective page width. Page size: FPDF(orientation="L", format="A4"). Header/footer: override header() and footer() methods. HTML: from fpdf import HTMLMixin. pdf.write_html("<b>bold</b><br><table>..."). Output bytes: pdf.output() — returns bytes. pdf.output("file.pdf") — writes file. Claude Code generates fpdf2 invoice renderers, report templates, and PDF pipelines.

CLAUDE.md for fpdf2

## fpdf2 Stack
- Version: fpdf2 >= 2.7 | pip install fpdf2
- Init: FPDF(); pdf.add_page(); pdf.set_font("Helvetica", "B", 14)
- Cell: pdf.cell(w, h, text, border=1, align="C", fill=True) — w=0 = full width
- Wrap: pdf.multi_cell(0, 8, long_text) — auto line-break at page width
- Color: pdf.set_fill_color(r,g,b) | set_text_color | set_draw_color
- Image: pdf.image("path", x, y, w) — PNG/JPEG; pass BytesIO for in-memory
- Output: pdf.output("file.pdf") | bytes_pdf = pdf.output() for HTTP response

fpdf2 PDF Generation Pipeline

# app/pdf_gen.py — fpdf2 invoice, report, and table PDF generators
from __future__ import annotations

import io
from dataclasses import dataclass
from datetime import date
from typing import Any

from fpdf import FPDF, FPDFException


# ─────────────────────────────────────────────────────────────────────────────
# 1. Base document class with header/footer
# ─────────────────────────────────────────────────────────────────────────────

class BasePDF(FPDF):
    """
    Subclass FPDF and override header() / footer() for consistent branding.
    header() is called automatically at the start of each new page.
    footer() is called automatically before each page ends.
    """

    def __init__(
        self,
        company: str = "My Company",
        logo_path: str | None = None,
        **kwargs,
    ) -> None:
        super().__init__(**kwargs)
        self.company   = company
        self.logo_path = logo_path
        self.set_auto_page_break(auto=True, margin=20)
        self.add_page()

    def header(self) -> None:
        # Logo
        if self.logo_path:
            try:
                self.image(self.logo_path, x=10, y=8, w=30)
            except FPDFException:
                pass

        # Company name
        self.set_font("Helvetica", "B", 16)
        self.set_text_color(40, 40, 40)
        self.cell(0, 10, self.company, align="R")
        self.ln(12)
        # Separator line
        self.set_draw_color(200, 200, 200)
        self.line(10, self.get_y(), self.w - 10, self.get_y())
        self.ln(4)

    def footer(self) -> None:
        self.set_y(-15)
        self.set_font("Helvetica", "I", 8)
        self.set_text_color(150, 150, 150)
        self.cell(0, 10, f"Page {self.page_no()}", align="C")

    def section_title(self, title: str) -> None:
        """Styled section header."""
        self.set_font("Helvetica", "B", 12)
        self.set_fill_color(240, 240, 240)
        self.set_text_color(50, 50, 50)
        self.cell(0, 8, f"  {title}", fill=True)
        self.ln(10)

    def body_text(self, text: str, line_height: int = 6) -> None:
        """Regular body paragraph with auto word-wrap."""
        self.set_font("Helvetica", size=10)
        self.set_text_color(60, 60, 60)
        self.multi_cell(0, line_height, text)
        self.ln(3)


# ─────────────────────────────────────────────────────────────────────────────
# 2. Invoice generator
# ─────────────────────────────────────────────────────────────────────────────

@dataclass
class LineItem:
    description: str
    quantity: float
    unit_price: float

    @property
    def total(self) -> float:
        return self.quantity * self.unit_price


def generate_invoice(
    invoice_number: str,
    invoice_date: date,
    due_date: date,
    client: dict[str, str],
    items: list[LineItem],
    tax_rate: float = 0.10,
    company: str = "My Company",
    notes: str = "",
) -> bytes:
    """
    Generate a PDF invoice.
    Returns the PDF as bytes for HTTP response or file write.
    """
    pdf = BasePDF(company=company, orientation="P", format="A4")
    pdf.set_margins(15, 15, 15)

    # Invoice metadata
    pdf.set_font("Helvetica", "B", 22)
    pdf.set_text_color(50, 50, 50)
    pdf.cell(0, 12, "INVOICE", align="C")
    pdf.ln(8)

    # Invoice number / dates — two columns
    col_w = (pdf.epw - 10) / 2
    pdf.set_font("Helvetica", size=10)
    pdf.set_text_color(80, 80, 80)
    pdf.cell(col_w, 6, f"Invoice #: {invoice_number}")
    pdf.cell(col_w, 6, f"Bill To: {client.get('name', '')}", align="R")
    pdf.ln(6)
    pdf.cell(col_w, 6, f"Date: {invoice_date.strftime('%B %d, %Y')}")
    pdf.cell(col_w, 6, client.get("address", ""), align="R")
    pdf.ln(6)
    pdf.cell(col_w, 6, f"Due: {due_date.strftime('%B %d, %Y')}")
    pdf.cell(col_w, 6, client.get("city", ""), align="R")
    pdf.ln(10)

    # Table header
    col_widths = [pdf.epw * 0.50, pdf.epw * 0.15, pdf.epw * 0.17, pdf.epw * 0.18]
    headers    = ["Description", "Qty", "Unit Price", "Total"]

    pdf.set_fill_color(50, 50, 50)
    pdf.set_text_color(255, 255, 255)
    pdf.set_font("Helvetica", "B", 10)
    for w, h in zip(col_widths, headers):
        pdf.cell(w, 8, h, align="C", fill=True)
    pdf.ln()

    # Table rows (alternating shading)
    subtotal = 0.0
    for i, item in enumerate(items):
        fill = i % 2 == 0
        pdf.set_fill_color(248, 248, 248)
        pdf.set_text_color(50, 50, 50)
        pdf.set_font("Helvetica", size=9)

        pdf.cell(col_widths[0], 7, item.description, fill=fill)
        pdf.cell(col_widths[1], 7, str(item.quantity), align="C", fill=fill)
        pdf.cell(col_widths[2], 7, f"${item.unit_price:,.2f}", align="R", fill=fill)
        pdf.cell(col_widths[3], 7, f"${item.total:,.2f}", align="R", fill=fill)
        pdf.ln()
        subtotal += item.total

    # Totals section
    pdf.ln(4)
    tax     = subtotal * tax_rate
    total   = subtotal + tax
    right_x = pdf.epw * 0.60

    def total_row(label: str, amount: float, bold: bool = False) -> None:
        pdf.set_x(15 + right_x)
        pdf.set_font("Helvetica", "B" if bold else "", 10)
        pdf.set_text_color(50, 50, 50)
        pdf.cell(pdf.epw * 0.22, 7, label)
        pdf.cell(pdf.epw * 0.18, 7, f"${amount:,.2f}", align="R")
        pdf.ln()

    total_row("Subtotal:", subtotal)
    total_row(f"Tax ({tax_rate:.0%}):", tax)
    # Separator
    pdf.set_draw_color(180, 180, 180)
    pdf.line(15 + right_x, pdf.get_y(), pdf.w - 15, pdf.get_y())
    pdf.ln(1)
    total_row("TOTAL:", total, bold=True)

    # Notes
    if notes:
        pdf.ln(8)
        pdf.section_title("Notes")
        pdf.body_text(notes)

    return pdf.output()


# ─────────────────────────────────────────────────────────────────────────────
# 3. Data table report
# ─────────────────────────────────────────────────────────────────────────────

def generate_table_report(
    title: str,
    columns: list[str],
    rows: list[list[Any]],
    col_widths: list[float] | None = None,
    company: str = "My Company",
    orientation: str = "P",
) -> bytes:
    """Generate a PDF with a data table. Auto-distributes column widths if not provided."""
    pdf = BasePDF(
        company=company,
        orientation=orientation,  # "L" for landscape wide tables
        format="A4",
    )
    pdf.set_margins(10, 10, 10)

    # Title
    pdf.set_font("Helvetica", "B", 16)
    pdf.set_text_color(40, 40, 40)
    pdf.cell(0, 10, title, align="C")
    pdf.ln(12)

    # Column widths
    n = len(columns)
    widths = col_widths or [pdf.epw / n] * n

    # Header row
    pdf.set_fill_color(70, 130, 180)
    pdf.set_text_color(255, 255, 255)
    pdf.set_font("Helvetica", "B", 9)
    for w, col in zip(widths, columns):
        pdf.cell(w, 8, str(col), border=1, align="C", fill=True)
    pdf.ln()

    # Data rows
    pdf.set_font("Helvetica", size=9)
    for i, row in enumerate(rows):
        fill = i % 2 == 0
        pdf.set_fill_color(245, 245, 250) if fill else pdf.set_fill_color(255, 255, 255)
        pdf.set_text_color(40, 40, 40)
        for w, cell in zip(widths, row):
            pdf.cell(w, 7, str(cell), border="LR", fill=True)
        pdf.ln()
    # Bottom border
    for w in widths:
        pdf.cell(w, 0, "", border="T")
    pdf.ln(6)

    pdf.set_font("Helvetica", "I", 8)
    pdf.set_text_color(130, 130, 130)
    pdf.cell(0, 6, f"Total: {len(rows)} row(s)")

    return pdf.output()


# ─────────────────────────────────────────────────────────────────────────────
# 4. Flask response helper
# ─────────────────────────────────────────────────────────────────────────────

FLASK_EXAMPLE = '''
from flask import Flask, Response
from app.pdf_gen import generate_invoice, LineItem
from datetime import date

app = Flask(__name__)

@app.get("/invoice/<int:invoice_id>")
def invoice_pdf(invoice_id: int):
    items = [
        LineItem("Consulting services", 8, 150.00),
        LineItem("Code review",         2,  95.00),
    ]
    pdf_bytes = generate_invoice(
        invoice_number=f"INV-{invoice_id:04d}",
        invoice_date=date.today(),
        due_date=date.today().replace(day=28),
        client={"name": "Acme Corp", "address": "123 Main St", "city": "Springfield"},
        items=items,
        tax_rate=0.10,
    )
    return Response(
        pdf_bytes,
        mimetype="application/pdf",
        headers={"Content-Disposition": f"attachment; filename=invoice-{invoice_id}.pdf"},
    )
'''


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    from pathlib import Path

    print("=== Generating invoice.pdf ===")
    items = [
        LineItem("Python consulting",        10, 200.00),
        LineItem("Code review & refactoring", 4, 150.00),
        LineItem("Documentation",             2,  80.00),
    ]
    pdf_bytes = generate_invoice(
        invoice_number="INV-0042",
        invoice_date=date(2024, 1, 15),
        due_date=date(2024, 2, 15),
        client={
            "name":    "Acme Corporation",
            "address": "456 Commerce Blvd",
            "city":    "San Francisco, CA 94102",
        },
        items=items,
        tax_rate=0.085,
        company="Claude Skills LLC",
        notes="Thank you for your business! Payment is due within 30 days.",
    )
    Path("/tmp/invoice.pdf").write_bytes(pdf_bytes)
    print(f"  Written {len(pdf_bytes):,} bytes to /tmp/invoice.pdf")

    print("\n=== Generating report.pdf ===")
    columns = ["Name", "Department", "Sales ($)", "Target ($)", "% Target"]
    rows = [
        ["Alice Johnson",  "West",    "142,000", "130,000", "109%"],
        ["Bob Martinez",   "East",    "98,500",  "120,000",  "82%"],
        ["Carol Williams", "Central", "175,200", "150,000", "117%"],
        ["David Chen",     "North",   "61,000",   "90,000",  "68%"],
    ]
    report_bytes = generate_table_report(
        "Q4 Sales Performance",
        columns, rows,
        company="Sales Analytics Inc",
        orientation="L",
    )
    Path("/tmp/report.pdf").write_bytes(report_bytes)
    print(f"  Written {len(report_bytes):,} bytes to /tmp/report.pdf")

For the reportlab alternative — ReportLab is more powerful for complex documents (flowable layouts, vector graphics, platypus story model), but fpdf2’s immediate-mode API is much simpler for straightforward documents: pdf.cell(w, h, text) maps directly to the position model, and generating an invoice requires only add_page, set_font, cell, and multi_cell — no flowables, story lists, or frame objects. For the WeasyPrint / pdfkit alternative — WeasyPrint and pdfkit convert HTML/CSS to PDF, which is the right approach when you already have an HTML template (Jinja2 → WeasyPrint is a clean pipeline), but they require OS-level dependencies (wkhtmltopdf, Cairo, Pango); fpdf2 is a pure-Python PDF writer with no binary dependencies, making it easier to deploy in containers and Lambda functions. The Claude Skills 360 bundle includes fpdf2 skill sets covering FPDF initialization with orientation and format, header() and footer() override for page templates, cell() with width/height/text/border/align/fill, multi_cell() for auto-wrapping text, set_fill_color/set_text_color/set_draw_color, image() for PNG/JPEG embedding, set_x/set_y/set_xy for positioning, epw effective page width, section_title and body_text helpers, generate_invoice with line items and tax, generate_table_report with alternating rows and auto column widths, and Flask Response PDF download pattern. Start with the free tier to try PDF document generation code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free