/research:python-document-generationfrom research
Use when Python must generate downloadable Excel, Word, or PDF artefacts for application users with branding, charts, tables, formulas, and delivery controls; use the format-specific skill when only one document type needs manual production.
Ships in research. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.
python-document-generation or would be better handled by a more specific companion skill.references only as needed.SKILL.md first, then load only the referenced deep-dive files that are necessary for the task.| Category | Artifact | Format | Example |
|---|---|---|---|
| Correctness | Document export test plan | Markdown doc covering Excel/Word/PDF rendering for layout, fonts, images, and pagination | docs/python/doc-gen-tests.md |
references/ directory for deep detail after reading the core workflow below.| Artefact | Source or provider | Requirement | If absent |
|---|---|---|---|
| Verified data, output schema, brand assets, and delivery constraints | application and content owner | required | Return a generator contract if execution or rendering is unavailable |
Read access to source data, generator code, brand assets, and delivery constraints is required. Code edits and execution need explicit authority; deployment, storage writes, and user delivery require separate production permission.
If dependencies, execution, or rendering are unavailable, return a qualified generator contract or patch, identify untested formats, and leave reconciliation and visual checks unassessed.
| Choice | Action | Failure avoided |
|---|---|---|
| Large or slow document may exceed request limits | Queue generation and expose status | Request timeout or duplicate generation |
| Artefact | Consumer | Observable acceptance condition |
|---|---|---|
| Generator, generated artefact, and validation evidence | application user and engineering team | File opens, data reconciles, and format-specific render checks pass |
Generate a branded report from fixed test data, verify totals against the source, render representative pages, and test the download response.
How we produce beautiful, branded, downloadable Excel / Word / PDF files from Python. These are end-user artifacts — professional enough to send to clients, file with auditors, or hand to executives.
Prerequisites: Load python-modern-standards and python-saas-integration before this skill. Load python-data-analytics when the input is a DataFrame.
File < 500KB AND < 1s to generate -> Sidecar, return file bytes or stream
File 500KB – 5MB -> Sidecar, write to storage, return signed URL
File > 5MB OR > 2s to generate -> Worker, enqueue job, notify on completion
Scheduled / recurring reports -> Worker
Sync path: FastAPI endpoint returns FileResponse or a signed URL to a just-written file.
Async path: PHP enqueues job → worker generates file → worker writes to storage → worker notifies PHP via webhook or DB flag → PHP emails user or marks as ready.
See python-saas-integration → references/file-handoff.md for the full delivery pattern.
Both libraries are good. Pick per use case:
| Feature | openpyxl | xlsxwriter |
|---|---|---|
| Read existing .xlsx | Yes | No |
| Modify existing .xlsx | Yes | No |
| Write new .xlsx | Yes | Yes |
| Charts | Basic | Rich, Excel-like |
| Conditional formatting | Yes | Yes (more features) |
| Pivot tables | Read only | No |
| Write speed (large files) | Slower | Faster (memory-optimized mode) |
| Formulas | Yes | Yes |
| Images | Yes | Yes |
Rule: xlsxwriter for new multi-sheet dashboards with heavy formatting. openpyxl when you need to read/modify a template the client provided or when you need pivot tables.
A well-designed dashboard workbook has a consistent structure:
Skeleton (xlsxwriter):
import xlsxwriter
wb = xlsxwriter.Workbook(path, {"constant_memory": True, "default_date_format": "yyyy-mm-dd"})
brand = Brand.from_tenant(tenant) # see branding-system.md
fmt_title = wb.add_format({"bold": True, "font_size": 18, "font_color": brand.primary, "font_name": "Inter"})
fmt_kpi_label = wb.add_format({"bold": True, "font_color": "#555", "font_size": 10})
fmt_kpi_value = wb.add_format({"bold": True, "font_size": 24, "font_color": brand.primary, "num_format": "#,##0"})
fmt_header = wb.add_format({"bold": True, "bg_color": brand.primary, "font_color": "white", "border": 1})
fmt_currency = wb.add_format({"num_format": "#,##0.00"})
fmt_percent = wb.add_format({"num_format": "0.0%"})
cover = wb.add_worksheet("Cover")
cover.hide_gridlines(2)
cover.insert_image("B2", logo_path, {"x_scale": 0.5, "y_scale": 0.5})
cover.write("B8", f"{tenant.name} — Sales Dashboard", fmt_title)
cover.write("B9", f"Period: {period_start:%b %Y} – {period_end:%b %Y}", fmt_kpi_label)
cover.write("B10", f"Generated {datetime.now(UTC):%Y-%m-%d %H:%M UTC}", fmt_kpi_label)
cover.set_column("B:B", 50)
Full multi-sheet dashboard template (KPIs, charts, conditional formatting, formulas, pivots when openpyxl, protection) in references/excel-dashboard-patterns.md.
python-docx is the standard. It gives fine control over paragraphs, runs, tables, and sections, but some things (page borders, complex headers) are set via direct OXML.
Structure of a branded report:
See references/word-python-docx.md for the letterhead template, style setup, and the helpers we use to avoid fighting with OXML for common needs.
Two philosophies:
Pick weasyprint when: marketing/brand-heavy layouts, designer-provided HTML, reusing existing CSS. Requires Cairo/Pango system libs on the server.
Pick reportlab when: data-dense financial output, fine-grained paginated tables, no system dependencies.
Minimal reportlab example:
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image, PageBreak
)
doc = SimpleDocTemplate(path, pagesize=A4,
leftMargin=20*mm, rightMargin=20*mm,
topMargin=25*mm, bottomMargin=20*mm)
styles = getSampleStyleSheet()
h1 = ParagraphStyle("h1", parent=styles["Heading1"], textColor=colors.HexColor(brand.primary), fontName="Helvetica-Bold")
story = [
Image(logo_path, width=40*mm, height=15*mm),
Spacer(1, 10*mm),
Paragraph(f"{tenant.name} — Monthly Report", h1),
Paragraph(f"Period: {period}", styles["Normal"]),
Spacer(1, 8*mm),
Table(table_data, style=TableStyle([...]), repeatRows=1),
]
doc.build(story, onFirstPage=header_footer, onLaterPages=header_footer)
See references/pdf-reportlab.md and references/pdf-weasyprint.md.
Static PNG/SVG from matplotlib (for clarity, use a limited palette aligned to brand; set figure DPI to 150+ for print quality).
import matplotlib
matplotlib.use("Agg") # no GUI backend — critical on servers
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 3.5), dpi=150)
ax.plot(df.index, df["mrr"], color=brand.primary, linewidth=2)
ax.fill_between(df.index, df["mrr"], color=brand.primary, alpha=0.1)
ax.set_title("MRR trend", pad=12)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
fig.savefig(png_path, dpi=150, bbox_inches="tight")
plt.close(fig) # always close — leaks otherwise
Never use pyplot stateful API in a worker. Always create explicit fig, ax. Always plt.close(fig) — matplotlib leaks memory otherwise and workers will OOM after a few hundred charts.
See references/charts-for-embedding.md for plotly static export and the style guide for chart brand consistency.
One source of truth for brand across all output types.
@dataclass(frozen=True)
class Brand:
primary: str # hex, e.g., "#0B5FFF"
secondary: str
text: str = "#111827"
muted: str = "#6B7280"
success: str = "#059669"
danger: str = "#DC2626"
warning: str = "#D97706"
font_family: str = "Inter"
logo_path: Path
footer_tagline: str = ""
@classmethod
def from_tenant(cls, tenant: Tenant) -> "Brand":
return cls(
primary=tenant.brand_color_primary or "#0B5FFF",
secondary=tenant.brand_color_secondary or "#6B7280",
logo_path=tenant.logo_path,
footer_tagline=tenant.footer_tagline or "",
)
Reuse the same Brand object in Excel (format colors), Word (style colors, logo), and PDF (reportlab colors, weasyprint CSS vars). See references/branding-system.md.
application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentapplication/pdfContent-Disposition: attachment; filename*=UTF-8''<url-encoded>.xlsx. Support non-ASCII tenant names.DownloadManager / iOS URLSession both handle signed URLs fine. For in-app preview, return a PDF (both platforms have native previewers); Excel/Word require a system app.<tenant-slug>_<report-type>_<period>_<timestamp>.<ext> — always include period and timestamp so users can keep multiple versions.See references/delivery-and-downloads.md.
1. PHP user requests report (clicks Generate)
2. PHP enqueues job with payload + idempotency_key
-> responds 202 Accepted with job_id
3. Client polls /jobs/{id} every 3s OR PHP sends push/email when ready
4. Worker picks up job:
a. Loads data (pandas / SQL)
b. Generates file (xlsxwriter / python-docx / reportlab)
c. Writes to storage under tenant_id/reports/{job_id}/...
d. Updates job status: completed, file_url=signed_url
5. Client downloads the file
Always write the file to a temp path first, then atomic-rename on success. Never expose partial files.
constant_memory=True for > 100K rows. openpyxl has write_only=True mode.matplotlib.use("Agg") + a process pool. Threads won't help for matplotlib.MemoryMax= set. Kill runaway jobs rather than swap.See references/performance.md.
canvas.Canvas when platypus flowables would do — fragile.references/excel-openpyxl-vs-xlsxwriter.mdreferences/excel-dashboard-patterns.mdreferences/word-python-docx.mdreferences/pdf-reportlab.mdreferences/pdf-weasyprint.mdreferences/charts-for-embedding.mdreferences/branding-system.mdreferences/delivery-and-downloads.mdreferences/performance.mdexcel-spreadsheets skill — design principles for professional Excel output (complements the Python implementation here).professional-word-output skill — design principles for Word documents.data-visualization skill — Knaflic's storytelling principles; apply these to every chart.report-print-pdf skill — HTML/mPDF counterpart in PHP.| Evidence | Consumer | Acceptance |
|---|---|---|
| Generator tests, reconciliation, and render-QA record | Engineering and release owner | Files open, source totals match, and format checks are recorded |
references/branding-system.md (opens in a new tab)references/charts-for-embedding.md (opens in a new tab)references/delivery-and-downloads.md (opens in a new tab)references/excel-dashboard-patterns.md (opens in a new tab)references/excel-openpyxl-vs-xlsxwriter.md (opens in a new tab)references/pdf-reportlab.md (opens in a new tab)references/pdf-weasyprint.md (opens in a new tab)references/performance.md (opens in a new tab)references/word-python-docx.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
59 skills in this plugin
/00-meta-initializationUse when starting a scaffolded research workspace that needs an explicit project profile, methodology, audience-output matrix, wave roadmap, and dispatch gate; do not use for routine work inside an already initialised project./academic-reporting-standardsUse when an academic paper, thesis, dissertation, journal article, systematic review, or examinable artefact must follow a named reporting or examination standard; use academic-writing instead for prose craft without a reporting-standard decision./academic-writingUse when drafting or revising an academic paper, essay, thesis, or dissertation with source-away composition, originality, citation, synthesis, voice, and register controls; use academic-reporting-standards for selecting formal study-reporting rules.Other plugins' skills for the same job
npx claudepluginhub peterbamuhigire/chwezi-research-engine --plugin research