PDF Skill
When To Use
- Read or review PDF content where layout and visuals matter.
- Create PDFs programmatically with reliable formatting.
- Fill and validate interactive PDF forms.
- Validate final rendering before delivery.
Workflow
- Prefer visual review: render PDF pages to PNGs and inspect them.
- Use
pdftoppm from the bundled runtime or system Poppler when available.
- If unavailable, install Poppler or ask the user to review the output locally.
- Use
reportlab to generate PDFs when creating new documents.
- Use
pdfplumber or pypdf for text extraction and quick checks; do not rely on text extraction for layout fidelity.
- After each meaningful update, re-render pages and verify alignment, spacing, and legibility.
Fill And Validate AcroForms
Visual review alone is not a correctness check for a fillable PDF. A page /Widget annotation can render a value from its appearance stream while the canonical /AcroForm/Fields tree is missing or contains a stale value.
- Keep the result interactive by default; set
flatten=True only when the user explicitly requests a completed, static form. Preserve the source PDF, and do not flatten a signed PDF without an explicit workflow decision.
- Inspect both representations before filling: enumerate fields from
reader.get_fields() and /Widget annotations from every page's /Annots, following /Parent and /Kids. If a widget and a canonical field have the same name but are distinct objects with no /Parent relationship, do not call reattach_fields() blindly: it can create a second top-level field with the same name. Report the ambiguity or produce a static result.
- Recover genuinely orphaned widgets, fill all pages, and write the result with
pypdf:
from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject
reader = PdfReader(input_pdf)
writer = PdfWriter()
writer.clone_document_from_reader(reader)
# Restores widgets that are missing from /AcroForm/Fields.
writer.reattach_fields()
fields = writer.get_fields() or {}
missing = set(expected_values) - set(fields)
if missing:
raise ValueError(f"Form fields not found after repair: {sorted(missing)}")
values_to_write = dict(expected_values)
if flatten:
# Paint every existing value before removing every widget.
values_to_write = {
name: field.get("/V", "/Off" if field.get("/FT") == "/Btn" else "")
for name, field in fields.items()
}
values_to_write.update(expected_values)
writer.update_page_form_field_values(
None, values_to_write, auto_regenerate=False, flatten=flatten
)
if flatten:
# pypdf's flatten=True paints appearances but does not remove widgets.
writer.remove_annotations(subtypes="/Widget")
writer.root_object.pop(NameObject("/AcroForm"), None)
with open(output_pdf, "wb") as stream:
writer.write(stream)
- Reopen the written PDF before delivery. For an interactive result, require every expected field to be present in
get_fields() with the expected /V, enumerate page widgets again, and confirm their effective /V (the widget value or inherited /Parent value) agrees. Confirm each updated widget has a non-empty /AP /N appearance and render the final pages to catch stale or clipped appearances. Do not rely on /NeedAppearances or a successful PNG render as proof that logical field data was updated.
- For a flattened result, require zero
/Widget annotations and no remaining /AcroForm field tree after reopening, then render the final pages. Keep an editable copy when the user may need to revise the form.
Temp And Output Conventions
- Use
tmp/pdfs/ for intermediate files; delete them when done.
- Write final artifacts under
output/pdf/ when working in this repo.
- Keep filenames stable and descriptive.
Dependencies
Prefer the Codex bundled workspace/runtime dependencies when available. The primary runtime is expected to include:
- Python packages:
reportlab, pdfplumber, pypdf
- Rendering tools:
pdftoppm and pdfinfo from Poppler
If a dependency is missing, install only what is needed.
Python packages:
uv pip install reportlab pdfplumber pypdf
If uv is unavailable:
python3 -m pip install reportlab pdfplumber pypdf
System tools for rendering:
# macOS (Homebrew)
brew install poppler
# Ubuntu/Debian
sudo apt-get install -y poppler-utils
If installation is not possible in this environment, tell the user which dependency is missing and how to install it locally.
Environment
No required environment variables.
Rendering Command
pdftoppm -png "$INPUT_PDF" "$OUTPUT_PREFIX"
Quality Expectations
- Maintain polished visual design: consistent typography, spacing, margins, and section hierarchy.
- Avoid rendering issues: clipped text, overlapping elements, broken tables, black squares, or unreadable glyphs.
- Charts, tables, and images must be sharp, aligned, and clearly labeled.
- Use ASCII hyphens only. Avoid U+2011 and other Unicode dashes.
- Citations and references must be human-readable; never leave tool tokens or placeholder strings.
Final Checks
- Do not deliver until the latest PNG inspection shows zero visual or formatting defects.
- Confirm headers, footers, page numbering, and section transitions look polished.
- Keep intermediate files organized or remove them after final approval.
Final response citations
Place :codex-file-citation{...} inline in prose, not in a trailing list. Use purpose="source" for Q&A/no-op and purpose="output" for create/edit.
- [HARD REQUIREMENT] Create/edit: cite each final PDF exactly once with a plain output citation. Summarize representative changes; do not cite every page or add a separate filename, path, or Markdown link. Example:
Created :codex-file-citation{path="/abs/path/report.pdf" purpose="output"}, with the completed analysis and appendix.
- Q&A/no-op: do not edit or re-export. Inspect the complete relevant pages, preserve material headings, table/figure labels, footnotes, sources, and sample sizes, and cite each source PDF once with a plain source citation.
PDF citations currently support only plain file citations. Do not add artifact_kind, page_number, or other locators. Never cite rendered PNGs, scratch files, builders, or QA intermediates unless asked.
1---
2name: pdf-2
3description: "Read, create, inspect, render, and verify PDF files where visual layout matters, including fillable AcroForms. Use Poppler rendering plus Python tools such as reportlab, pdfplumber, and pypdf for generation and extraction."
4metadata:
5 source: https://skillmd.com/skills/ahang1598/pdf-2
6---
7
8# PDF Skill
9
10## When To Use
11
12- Read or review PDF content where layout and visuals matter.
13- Create PDFs programmatically with reliable formatting.
14- Fill and validate interactive PDF forms.
15- Validate final rendering before delivery.
16
17## Workflow
18
191. Prefer visual review: render PDF pages to PNGs and inspect them.
20 - Use `pdftoppm` from the bundled runtime or system Poppler when available.
21 - If unavailable, install Poppler or ask the user to review the output locally.
222. Use `reportlab` to generate PDFs when creating new documents.
233. Use `pdfplumber` or `pypdf` for text extraction and quick checks; do not rely on text extraction for layout fidelity.
244. After each meaningful update, re-render pages and verify alignment, spacing, and legibility.
25
26## Fill And Validate AcroForms
27
28Visual review alone is not a correctness check for a fillable PDF. A page `/Widget` annotation can render a value from its appearance stream while the canonical `/AcroForm/Fields` tree is missing or contains a stale value.
29
301. Keep the result interactive by default; set `flatten=True` only when the user explicitly requests a completed, static form. Preserve the source PDF, and do not flatten a signed PDF without an explicit workflow decision.
312. Inspect both representations before filling: enumerate fields from `reader.get_fields()` and `/Widget` annotations from every page's `/Annots`, following `/Parent` and `/Kids`. If a widget and a canonical field have the same name but are distinct objects with no `/Parent` relationship, do not call `reattach_fields()` blindly: it can create a second top-level field with the same name. Report the ambiguity or produce a static result.
323. Recover genuinely orphaned widgets, fill all pages, and write the result with `pypdf`:
33
34```python
35from pypdf import PdfReader, PdfWriter
36from pypdf.generic import NameObject
37
38reader = PdfReader(input_pdf)
39writer = PdfWriter()
40writer.clone_document_from_reader(reader)
41
42# Restores widgets that are missing from /AcroForm/Fields.
43writer.reattach_fields()
44fields = writer.get_fields() or {}
45missing = set(expected_values) - set(fields)
46if missing:
47 raise ValueError(f"Form fields not found after repair: {sorted(missing)}")
48
49values_to_write = dict(expected_values)
50if flatten:
51 # Paint every existing value before removing every widget.
52 values_to_write = {
53 name: field.get("/V", "/Off" if field.get("/FT") == "/Btn" else "")
54 for name, field in fields.items()
55 }
56 values_to_write.update(expected_values)
57
58writer.update_page_form_field_values(
59 None, values_to_write, auto_regenerate=False, flatten=flatten
60)
61
62if flatten:
63 # pypdf's flatten=True paints appearances but does not remove widgets.
64 writer.remove_annotations(subtypes="/Widget")
65 writer.root_object.pop(NameObject("/AcroForm"), None)
66
67with open(output_pdf, "wb") as stream:
68 writer.write(stream)
69```
70
714. Reopen the written PDF before delivery. For an interactive result, require every expected field to be present in `get_fields()` with the expected `/V`, enumerate page widgets again, and confirm their effective `/V` (the widget value or inherited `/Parent` value) agrees. Confirm each updated widget has a non-empty `/AP` `/N` appearance and render the final pages to catch stale or clipped appearances. Do not rely on `/NeedAppearances` or a successful PNG render as proof that logical field data was updated.
725. For a flattened result, require zero `/Widget` annotations and no remaining `/AcroForm` field tree after reopening, then render the final pages. Keep an editable copy when the user may need to revise the form.
73
74## Temp And Output Conventions
75
76- Use `tmp/pdfs/` for intermediate files; delete them when done.
77- Write final artifacts under `output/pdf/` when working in this repo.
78- Keep filenames stable and descriptive.
79
80## Dependencies
81
82Prefer the Codex bundled workspace/runtime dependencies when available. The primary runtime is expected to include:
83
84- Python packages: `reportlab`, `pdfplumber`, `pypdf`
85- Rendering tools: `pdftoppm` and `pdfinfo` from Poppler
86
87If a dependency is missing, install only what is needed.
88
89Python packages:
90
91```bash
92uv pip install reportlab pdfplumber pypdf
93```
94
95If `uv` is unavailable:
96
97```bash
98python3 -m pip install reportlab pdfplumber pypdf
99```
100
101System tools for rendering:
102
103```bash
104# macOS (Homebrew)
105brew install poppler
106
107# Ubuntu/Debian
108sudo apt-get install -y poppler-utils
109```
110
111If installation is not possible in this environment, tell the user which dependency is missing and how to install it locally.
112
113## Environment
114
115No required environment variables.
116
117## Rendering Command
118
119```bash
120pdftoppm -png "$INPUT_PDF" "$OUTPUT_PREFIX"
121```
122
123## Quality Expectations
124
125- Maintain polished visual design: consistent typography, spacing, margins, and section hierarchy.
126- Avoid rendering issues: clipped text, overlapping elements, broken tables, black squares, or unreadable glyphs.
127- Charts, tables, and images must be sharp, aligned, and clearly labeled.
128- Use ASCII hyphens only. Avoid U+2011 and other Unicode dashes.
129- Citations and references must be human-readable; never leave tool tokens or placeholder strings.
130
131## Final Checks
132
133- Do not deliver until the latest PNG inspection shows zero visual or formatting defects.
134- Confirm headers, footers, page numbering, and section transitions look polished.
135- Keep intermediate files organized or remove them after final approval.
136
137## Final response citations
138
139Place `:codex-file-citation{...}` inline in prose, not in a trailing list. Use `purpose="source"` for Q&A/no-op and `purpose="output"` for create/edit.
140
141- [HARD REQUIREMENT] Create/edit: cite each final PDF exactly once with a plain output citation. Summarize representative changes; do not cite every page or add a separate filename, path, or Markdown link. Example: `Created :codex-file-citation{path="/abs/path/report.pdf" purpose="output"}, with the completed analysis and appendix.`
142- Q&A/no-op: do not edit or re-export. Inspect the complete relevant pages, preserve material headings, table/figure labels, footnotes, sources, and sample sizes, and cite each source PDF once with a plain source citation.
143
144PDF citations currently support only plain file citations. Do not add `artifact_kind`, `page_number`, or other locators. Never cite rendered PNGs, scratch files, builders, or QA intermediates unless asked.