@nomad-e/bluma-cli 0.26.1 → 2026.27.0-darwin-arm64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +189 -70
- package/README.md +2 -162
- package/THIRD-PARTY-NOTICES.txt +46201 -0
- package/bin/bluma-core +0 -0
- package/package.json +24 -124
- package/third-party/option-ext/.cargo_vcs_info.json +6 -0
- package/third-party/option-ext/Cargo.toml +22 -0
- package/third-party/option-ext/LICENSE.txt +373 -0
- package/third-party/option-ext/README.md +67 -0
- package/third-party/option-ext/src/impl.rs +20 -0
- package/third-party/option-ext/src/lib.rs +71 -0
- package/assets/bg.png +0 -0
- package/assets/bg1.png +0 -0
- package/assets/bluma.png +0 -0
- package/assets/image.png +0 -0
- package/dist/assets/bg.png +0 -0
- package/dist/assets/bg1.png +0 -0
- package/dist/assets/bluma.png +0 -0
- package/dist/assets/image.png +0 -0
- package/dist/config/native_tools.json +0 -1151
- package/dist/config/plan_mode_instructions.md +0 -218
- package/dist/config/skills/factorai-sh/SKILL.md +0 -98
- package/dist/config/skills/git-commit/LICENSE.txt +0 -18
- package/dist/config/skills/git-commit/SKILL.md +0 -300
- package/dist/config/skills/git-commit/references/REFERENCE.md +0 -253
- package/dist/config/skills/git-commit/scripts/validate_commit_msg.py +0 -163
- package/dist/config/skills/git-pr/LICENSE.txt +0 -18
- package/dist/config/skills/git-pr/SKILL.md +0 -293
- package/dist/config/skills/git-pr/references/REFERENCE.md +0 -256
- package/dist/config/skills/git-pr/scripts/validate_commits.py +0 -120
- package/dist/config/skills/git-release/LICENSE.txt +0 -18
- package/dist/config/skills/git-release/SKILL.md +0 -408
- package/dist/config/skills/pdf/LICENSE.txt +0 -26
- package/dist/config/skills/pdf/SKILL.md +0 -736
- package/dist/config/skills/pdf/references/DOCUMENT_TYPES.md +0 -59
- package/dist/config/skills/pdf/references/FORMS.md +0 -69
- package/dist/config/skills/pdf/references/REFERENCE.md +0 -52
- package/dist/config/skills/pdf/scripts/__pycache__/create_report.cpython-312.pyc +0 -0
- package/dist/config/skills/pdf/scripts/create_report.py +0 -936
- package/dist/config/skills/pdf/scripts/merge_pdfs.py +0 -48
- package/dist/config/skills/skill-creator/LICENSE.txt +0 -26
- package/dist/config/skills/skill-creator/SKILL.md +0 -229
- package/dist/config/skills/xlsx/LICENSE.txt +0 -18
- package/dist/config/skills/xlsx/SKILL.md +0 -340
- package/dist/config/skills/xlsx/references/REFERENCE.md +0 -337
- package/dist/config/skills/xlsx/scripts/office/__init__.py +0 -2
- package/dist/config/skills/xlsx/scripts/office/pack.py +0 -58
- package/dist/config/skills/xlsx/scripts/office/soffice.py +0 -180
- package/dist/config/skills/xlsx/scripts/office/unpack.py +0 -63
- package/dist/config/skills/xlsx/scripts/office/validate.py +0 -122
- package/dist/config/skills/xlsx/scripts/recalc.py +0 -152
- package/dist/main.js +0 -47918
- package/dist/native/bluma-clipboard.linux-x64-gnu.node +0 -0
- package/dist/native/index.d.ts +0 -38
- package/dist/native/index.js +0 -319
- package/dist/native/package.json +0 -38
- package/dist/scaffold/.eslintrc.json +0 -3
- package/dist/scaffold/app/globals.css +0 -46
- package/dist/scaffold/app/layout.tsx +0 -19
- package/dist/scaffold/app/page.tsx +0 -124
- package/dist/scaffold/components/ui/README.md +0 -12
- package/dist/scaffold/components/ui/accordion.jsx +0 -42
- package/dist/scaffold/components/ui/alert-dialog.jsx +0 -80
- package/dist/scaffold/components/ui/alert.jsx +0 -33
- package/dist/scaffold/components/ui/aspect-ratio.jsx +0 -5
- package/dist/scaffold/components/ui/avatar.jsx +0 -28
- package/dist/scaffold/components/ui/badge.jsx +0 -24
- package/dist/scaffold/components/ui/breadcrumb.jsx +0 -72
- package/dist/scaffold/components/ui/button.jsx +0 -40
- package/dist/scaffold/components/ui/calendar.jsx +0 -56
- package/dist/scaffold/components/ui/card.jsx +0 -38
- package/dist/scaffold/components/ui/carousel.jsx +0 -168
- package/dist/scaffold/components/ui/chart.jsx +0 -76
- package/dist/scaffold/components/ui/checkbox.jsx +0 -22
- package/dist/scaffold/components/ui/collapsible.jsx +0 -7
- package/dist/scaffold/components/ui/command.jsx +0 -100
- package/dist/scaffold/components/ui/context-menu.jsx +0 -137
- package/dist/scaffold/components/ui/dialog.jsx +0 -72
- package/dist/scaffold/components/ui/drawer.jsx +0 -68
- package/dist/scaffold/components/ui/dropdown-menu.jsx +0 -143
- package/dist/scaffold/components/ui/form.jsx +0 -88
- package/dist/scaffold/components/ui/hover-card.jsx +0 -22
- package/dist/scaffold/components/ui/input-otp.jsx +0 -49
- package/dist/scaffold/components/ui/input.jsx +0 -19
- package/dist/scaffold/components/ui/label.jsx +0 -15
- package/dist/scaffold/components/ui/menubar.jsx +0 -161
- package/dist/scaffold/components/ui/navigation-menu.jsx +0 -95
- package/dist/scaffold/components/ui/pagination.jsx +0 -77
- package/dist/scaffold/components/ui/popover.jsx +0 -25
- package/dist/scaffold/components/ui/progress.jsx +0 -19
- package/dist/scaffold/components/ui/radio-group.jsx +0 -29
- package/dist/scaffold/components/ui/resizable.jsx +0 -27
- package/dist/scaffold/components/ui/scroll-area.jsx +0 -31
- package/dist/scaffold/components/ui/select.jsx +0 -117
- package/dist/scaffold/components/ui/separator.jsx +0 -22
- package/dist/scaffold/components/ui/sheet.jsx +0 -81
- package/dist/scaffold/components/ui/skeleton.jsx +0 -7
- package/dist/scaffold/components/ui/slider.jsx +0 -19
- package/dist/scaffold/components/ui/sonner.jsx +0 -22
- package/dist/scaffold/components/ui/switch.jsx +0 -23
- package/dist/scaffold/components/ui/table.jsx +0 -61
- package/dist/scaffold/components/ui/tabs.jsx +0 -43
- package/dist/scaffold/components/ui/textarea.jsx +0 -18
- package/dist/scaffold/components/ui/toast.jsx +0 -85
- package/dist/scaffold/components/ui/toaster.jsx +0 -33
- package/dist/scaffold/components/ui/toggle-group.jsx +0 -41
- package/dist/scaffold/components/ui/toggle.jsx +0 -30
- package/dist/scaffold/components/ui/tooltip.jsx +0 -22
- package/dist/scaffold/hooks/use-toast.ts +0 -101
- package/dist/scaffold/lib/utils.ts +0 -6
- package/dist/scaffold/next.config.js +0 -5
- package/dist/scaffold/next.config.mjs +0 -15
- package/dist/scaffold/next.config.ts +0 -19
- package/dist/scaffold/package.json +0 -70
- package/dist/scaffold/postcss.config.js +0 -6
- package/dist/scaffold/tailwind.config.ts +0 -57
- package/dist/scaffold/tsconfig.json +0 -20
|
@@ -1,736 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: pdf
|
|
3
|
-
description: >
|
|
4
|
-
Use for any PDF task. For reports to mixed audiences (technical + lay readers),
|
|
5
|
-
set audience "mixed" and use plain_language + technical_note callouts per section.
|
|
6
|
-
For new reports prefer create_report.py --from-json with rich JSON (see
|
|
7
|
-
Comunicação técnico-científica in SKILL). Ad-hoc ReportLab = amateur PDFs.
|
|
8
|
-
Also extract/merge/OCR/forms. Triggers: .pdf, relatório, report, documento técnico.
|
|
9
|
-
license: Proprietary. LICENSE.txt has complete terms
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
# PDF — Professional Document Creation & Processing
|
|
13
|
-
|
|
14
|
-
## Design Philosophy
|
|
15
|
-
|
|
16
|
-
> Every PDF generated by BluMa must look like it was made by a professional
|
|
17
|
-
> design agency, not a script. Typography, spacing, color, and hierarchy are
|
|
18
|
-
> not optional — they are the foundation of a credible document.
|
|
19
|
-
|
|
20
|
-
## Prerequisites
|
|
21
|
-
|
|
22
|
-
- **Python 3.10+** installed and available in PATH
|
|
23
|
-
- Install dependencies: `pip install reportlab pypdf`
|
|
24
|
-
- If any script fails with `command not found` or `ModuleNotFoundError`, Python or its
|
|
25
|
-
packages are missing — install them before proceeding
|
|
26
|
-
|
|
27
|
-
## MANDATORY workflow — new multi-page reports (read first)
|
|
28
|
-
|
|
29
|
-
Ad-hoc 30-line ReportLab scripts are the #1 cause of “cheap PDF” output (no
|
|
30
|
-
cover hierarchy, ugly tables, random margins). **Do not do that** for anything
|
|
31
|
-
the user will share externally.
|
|
32
|
-
|
|
33
|
-
**Preferred (deliverable quality locked in):**
|
|
34
|
-
|
|
35
|
-
1. Read **references/DOCUMENT_TYPES.md** and set **`document_type`** (and
|
|
36
|
-
**`letterhead`** when the user wants papel timbrado / cabeçalho corporativo).
|
|
37
|
-
2. Build a UTF-8 JSON file with `title`, optional `subtitle` / `author`, and
|
|
38
|
-
`sections[]` (`num`, `title`, `blocks[]`). Follow the **JSON quality**
|
|
39
|
-
section below — not only the schema (see **Available Scripts** for types).
|
|
40
|
-
3. Run: `python /absolute/path/to/scripts/create_report.py --from-json
|
|
41
|
-
your.json --output .bluma/artifacts/your.pdf` (or the path in `artifacts_dir` from `task_boundary`)
|
|
42
|
-
4. Attach that **absolute** path as the deliverable. Do **not** paste huge
|
|
43
|
-
ReportLab source into the chat unless the user explicitly wants code.
|
|
44
|
-
|
|
45
|
-
### Pick the layout — do not use one template for everything
|
|
46
|
-
|
|
47
|
-
| User asks for | `document_type` | Notes |
|
|
48
|
-
|---------------|-----------------|-------|
|
|
49
|
-
| Relatório executivo, board, entrega formal | `executive_report` | Capa + sumário; quebras só em capítulos densos |
|
|
50
|
-
| Inventário hardware, specs, sistema | `technical` | Fluxo contínuo; tabelas com texto resumido (não IPv6 novel) |
|
|
51
|
-
|
|
52
|
-
### Inventário hardware — specs fornecidas pelo utilizador (sandbox)
|
|
53
|
-
|
|
54
|
-
When the user or envelope includes machine specs JSON (`hostname`, `fabricante`,
|
|
55
|
-
`cpu_modelo`, `ram_gb`, `os`, …) or a block `<dados_da_maquina_do_utilizador>`:
|
|
56
|
-
|
|
57
|
-
1. **Use only that data** in the PDF — it describes the **user's machine**, not the sandbox.
|
|
58
|
-
2. **Do not** run `hostname`, `lscpu`, `uname`, `dmidecode`, `inxi`, or similar to
|
|
59
|
-
"discover" hardware; that reads the **container/VM** and produces wrong reports.
|
|
60
|
-
3. Save the provided object to `.bluma/artifacts/machine.json` (UTF-8), map fields to
|
|
61
|
-
`sections[]` / `table` rows in your report JSON, then `create_report.py --from-json`.
|
|
62
|
-
4. Missing fields → omit or note "não fornecido" — **never** fill gaps from sandbox
|
|
63
|
-
`<environment>` or shell output.
|
|
64
|
-
| Carta, proposta, documento com marca | `letterhead` | Preencher `letterhead.organization`, morada, `logo_path` opcional |
|
|
65
|
-
| Nota curta | `memo` | Sem sumário |
|
|
66
|
-
| Artigo técnico, MCP, whitepaper | `article` | Sem capítulos numerados excessivos |
|
|
67
|
-
|
|
68
|
-
Override any preset with top-level `layout: { "include_toc": false, "page_break_per_section": false }`.
|
|
69
|
-
|
|
70
|
-
**Acceptable alternative:** copy `create_report.py` and edit only data / story
|
|
71
|
-
assembly — keep the same colors, margins, `cover_story`, `section`, `pro_table`,
|
|
72
|
-
`callout`, and `onFirstPage` / `onLaterPages` callbacks.
|
|
73
|
-
|
|
74
|
-
**Hard no (reads as unprofessional):** default ReportLab styles; wall of text
|
|
75
|
-
with no cover; tables without a styled header row; margins under 2cm; emoji in
|
|
76
|
-
corporate PDFs (font/rendering inconsistency); “nota rodapé” as raw
|
|
77
|
-
`canvas.drawString` for body paragraphs instead of `Paragraph` styles.
|
|
78
|
-
|
|
79
|
-
## Comunicação técnico-científica — público misto (técnico + leigo)
|
|
80
|
-
|
|
81
|
-
Use when the deliverable is a **technical, scientific, or enterprise report** read by
|
|
82
|
-
both specialists and non-specialists (management, clients, audit, mixed teams).
|
|
83
|
-
|
|
84
|
-
Set in JSON: `"audience": "mixed"` (alternatives: `"technical"` = só especialistas;
|
|
85
|
-
`"general"` = priorizar clareza; default implícito em relatórios empresariais:
|
|
86
|
-
**`mixed`** quando o pedido não especificar).
|
|
87
|
-
|
|
88
|
-
### Princípios (obrigatório em `audience: "mixed"`)
|
|
89
|
-
|
|
90
|
-
1. **Integridade dos dados** — números, unidades, nomes de sistemas e conclusões
|
|
91
|
-
factuais **não são simplificados até ficarem errados**. A precisão vem nas
|
|
92
|
-
tabelas e na nota técnica; a clareza vem no resumo em linguagem simples.
|
|
93
|
-
2. **Dupla camada por secção** (ritmo recomendado):
|
|
94
|
-
- 1× **`callout`** com `"variant": "plain_language"` — 2–4 frases: o que isto
|
|
95
|
-
significa para quem não é da área (sem jargão, sem siglas sem explicar).
|
|
96
|
-
- **`paragraph`** ou **`table`** com o detalhe técnico (dados completos mas
|
|
97
|
-
**resumidos** em células — não dumps de log).
|
|
98
|
-
- Opcional: **`callout`** `"variant": "technical_note"` para limitações,
|
|
99
|
-
método, ou definição de um termo (1–3 frases).
|
|
100
|
-
3. **Linguagem** — frases curtas; definir siglas na primeira ocorrência
|
|
101
|
-
(“MCP (Model Context Protocol)”); evitar tom marketing; evitar humor.
|
|
102
|
-
4. **Tabelas** — cabeçalhos claros; na coluna de valor, preferir texto legível
|
|
103
|
-
(“Ubuntu 24.04 LTS”) em vez de strings brutas; mover detalhe excessivo para nota
|
|
104
|
-
ou parágrafo seguinte.
|
|
105
|
-
5. **Não patronizar** — o bloco `plain_language` explica *significado*, não
|
|
106
|
-
repete a tabela palavra por palavra.
|
|
107
|
-
|
|
108
|
-
### Exemplo de blocos numa secção (`audience: "mixed"`)
|
|
109
|
-
|
|
110
|
-
```json
|
|
111
|
-
{
|
|
112
|
-
"num": 2,
|
|
113
|
-
"title": "Sistema operativo",
|
|
114
|
-
"blocks": [
|
|
115
|
-
{
|
|
116
|
-
"type": "callout",
|
|
117
|
-
"variant": "plain_language",
|
|
118
|
-
"title": "O essencial",
|
|
119
|
-
"text": "O computador corre Ubuntu 24.04, uma versão estável e suportada, em arquitetura de 64 bits. Está ligado há cerca de 10 horas desde o último reinício."
|
|
120
|
-
},
|
|
121
|
-
{
|
|
122
|
-
"type": "table",
|
|
123
|
-
"headers": ["Propriedade", "Valor"],
|
|
124
|
-
"rows": [
|
|
125
|
-
["SO", "Ubuntu 24.04.3 LTS"],
|
|
126
|
-
["Kernel", "6.17.x"],
|
|
127
|
-
["Arquitetura", "x64"],
|
|
128
|
-
["Uptime", "~10 h (36 736 s)"]
|
|
129
|
-
]
|
|
130
|
-
}
|
|
131
|
-
]
|
|
132
|
-
}
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
### Quando NÃO usar `mixed`
|
|
136
|
-
|
|
137
|
-
- Relatório só para engenharia/DevOps interno → `"audience": "technical"`.
|
|
138
|
-
- FAQ ou carta comercial → `memo` / `letterhead`, linguagem já simples.
|
|
139
|
-
|
|
140
|
-
## JSON quality — make the PDF look “designed”, not “filled in”
|
|
141
|
-
|
|
142
|
-
The `--from-json` pipeline already applies a **clean, modern, understated**
|
|
143
|
-
visual system (slate palette, one accent, generous margins, one chapter per
|
|
144
|
-
page by default). **Exaggerated styling is not available and not desired** —
|
|
145
|
-
quality comes from **editorial structure and copy**, not from shouting.
|
|
146
|
-
|
|
147
|
-
When you author JSON, treat it like briefing a human designer:
|
|
148
|
-
|
|
149
|
-
### Cover metadata (`title`, `subtitle`, `author`)
|
|
150
|
-
|
|
151
|
-
- **`title`**: specific and scannable (e.g. “Relatório de atividade — Agiweb”),
|
|
152
|
-
not a generic “Relatório”. Length is OK; the script balances line breaks.
|
|
153
|
-
- **`subtitle`**: one line that states **scope or period** (what this PDF is
|
|
154
|
-
for). Avoid marketing fluff.
|
|
155
|
-
- **`author`**: organisation or product name the reader recognises; avoid
|
|
156
|
-
“Generated by AI” unless the user asked for it.
|
|
157
|
-
|
|
158
|
-
### Sections (`num`, `title`, `blocks`)
|
|
159
|
-
|
|
160
|
-
- Aim for **roughly 4–8 sections** for a typical executive note; merge thin
|
|
161
|
-
sections instead of many one-paragraph chapters.
|
|
162
|
-
- **Section titles**: concrete noun phrases (“Módulos ativos”, “Estado
|
|
163
|
-
operacional”) — not “Parte 2” or “Informações”.
|
|
164
|
-
- **Order inside a section** (good rhythm):
|
|
165
|
-
1. One or two **`paragraph`** blocks that set context (2–4 short sentences,
|
|
166
|
-
one main idea each; use `\n` only for a deliberate second paragraph).
|
|
167
|
-
2. Optionally an **`h2`** for a sub-topic if the section has two distinct
|
|
168
|
-
ideas.
|
|
169
|
-
3. **`bullets`** or **`table`** — not both back-to-back unless the second is
|
|
170
|
-
clearly “detail” after the first.
|
|
171
|
-
4. At most **one `callout`** per section, only for a decision, risk, or
|
|
172
|
-
single takeaway — not for every bullet.
|
|
173
|
-
|
|
174
|
-
### `paragraph`
|
|
175
|
-
|
|
176
|
-
- Prefer **facts, numbers, names** over vague adjectives (“significativo”,
|
|
177
|
-
“muito importante”). Write in the **same language** as the user’s request.
|
|
178
|
-
- Do not paste huge URLs or stack traces; summarise.
|
|
179
|
-
|
|
180
|
-
### `bullets`
|
|
181
|
-
|
|
182
|
-
- **Parallel wording** (all start with a verb, or all are noun phrases).
|
|
183
|
-
- **~3–8 items** per list in the body; move long enumerations to a **table** or
|
|
184
|
-
an appendix section.
|
|
185
|
-
- One line per item when possible; trim redundant words.
|
|
186
|
-
|
|
187
|
-
### `table`
|
|
188
|
-
|
|
189
|
-
- Prefer **2–5 columns**; headers are **short labels** (“Módulo”, “Estado”, not
|
|
190
|
-
sentences).
|
|
191
|
-
- Rows must be **readable at a glance**; paraphrase long statuses instead of
|
|
192
|
-
dumping raw log lines.
|
|
193
|
-
- Omit `col_widths` unless you need to weight columns; the generator normalises
|
|
194
|
-
widths.
|
|
195
|
-
|
|
196
|
-
### `callout` (`variant`: `info` | `warning` | `plain_language` | `technical_note`)
|
|
197
|
-
|
|
198
|
-
- **Info**: synthesis, definition, or “how to read this document”.
|
|
199
|
-
- **Warning**: real risk, compliance, or “requires action” — not routine stats.
|
|
200
|
-
- **plain_language**: mandatory in `audience: "mixed"` — explains meaning for
|
|
201
|
-
non-specialists (see section above).
|
|
202
|
-
- **technical_note**: precision, caveats, method, or definition — for specialists.
|
|
203
|
-
- **Title**: 2–5 words; **text**: 1–3 sentences. **Never** stack two callouts in
|
|
204
|
-
a row unless the second is `technical_note` after `plain_language`.
|
|
205
|
-
|
|
206
|
-
### `h2`
|
|
207
|
-
|
|
208
|
-
- Use sparingly inside long sections; keeps hierarchy without visual noise.
|
|
209
|
-
|
|
210
|
-
### `document_type`, `letterhead`, `layout`
|
|
211
|
-
|
|
212
|
-
- **`document_type`**: `executive_report` | `technical` | `letterhead` | `memo` | `article` (see DOCUMENT_TYPES.md).
|
|
213
|
-
- **`letterhead`**: `{ organization, department?, tagline?, address_lines[], contact?, logo_path? }` — obrigatório para timbrado.
|
|
214
|
-
- **`layout`**: `{ include_toc?, page_break_per_section?, cover_style?: corporate|minimal|letterhead }`.
|
|
215
|
-
|
|
216
|
-
### `page_break_per_section`
|
|
217
|
-
|
|
218
|
-
- Default **`false`** in the generator (evita páginas quase vazias).
|
|
219
|
-
- `executive_report` preset uses **`true`** only before **dense** sections (tabelas grandes ou muito texto).
|
|
220
|
-
- Inventários técnicos: manter **`false`**.
|
|
221
|
-
|
|
222
|
-
### Restraint checklist (before you run the script)
|
|
223
|
-
|
|
224
|
-
- [ ] Every section has at least one **substantive** `paragraph`, not only
|
|
225
|
-
bullets.
|
|
226
|
-
- [ ] No more than **one callout** per section unless the user explicitly wants
|
|
227
|
-
more.
|
|
228
|
-
- [ ] Tables are **small and meaningful**; no “spreadsheet dump”.
|
|
229
|
-
- [ ] No duplicated content between sumário-level titles and body.
|
|
230
|
-
- [ ] Tone is **professional and calm** — the layout already carries authority.
|
|
231
|
-
|
|
232
|
-
## MANDATORY: Professional Style System
|
|
233
|
-
|
|
234
|
-
Every PDF you create MUST use a consistent design system. Define these at the
|
|
235
|
-
top of every script BEFORE building any content.
|
|
236
|
-
|
|
237
|
-
### Color Palette
|
|
238
|
-
|
|
239
|
-
```python
|
|
240
|
-
from reportlab.lib.colors import HexColor
|
|
241
|
-
|
|
242
|
-
COLORS = {
|
|
243
|
-
# Keep in sync with scripts/create_report.py when editing custom code
|
|
244
|
-
'primary': HexColor('#0F172A'), # Slate — titles, table headers
|
|
245
|
-
'secondary': HexColor('#334155'), # Slate — subtitles, rules
|
|
246
|
-
'accent': HexColor('#C2410C'), # Burnt orange — rules, emphasis
|
|
247
|
-
'muted': HexColor('#64748B'),
|
|
248
|
-
'text': HexColor('#1E293B'),
|
|
249
|
-
'text_light': HexColor('#64748B'),
|
|
250
|
-
'bg_light': HexColor('#F1F5F9'),
|
|
251
|
-
'bg_accent': HexColor('#E0F2FE'),
|
|
252
|
-
'border': HexColor('#CBD5E1'),
|
|
253
|
-
'white': HexColor('#FFFFFF'),
|
|
254
|
-
'success': HexColor('#15803D'),
|
|
255
|
-
'danger': HexColor('#B91C1C'),
|
|
256
|
-
}
|
|
257
|
-
```
|
|
258
|
-
|
|
259
|
-
### Typography
|
|
260
|
-
|
|
261
|
-
```python
|
|
262
|
-
from reportlab.lib.styles import ParagraphStyle
|
|
263
|
-
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
|
|
264
|
-
|
|
265
|
-
FONT_BODY = 'Helvetica'
|
|
266
|
-
FONT_BOLD = 'Helvetica-Bold'
|
|
267
|
-
FONT_ITALIC = 'Helvetica-Oblique'
|
|
268
|
-
FONT_MONO = 'Courier'
|
|
269
|
-
|
|
270
|
-
STYLES = {
|
|
271
|
-
'doc_title': ParagraphStyle(
|
|
272
|
-
'DocTitle', fontName=FONT_BOLD, fontSize=28, leading=34,
|
|
273
|
-
textColor=COLORS['primary'], alignment=TA_CENTER,
|
|
274
|
-
spaceAfter=6,
|
|
275
|
-
),
|
|
276
|
-
'doc_subtitle': ParagraphStyle(
|
|
277
|
-
'DocSubtitle', fontName=FONT_BODY, fontSize=14, leading=18,
|
|
278
|
-
textColor=COLORS['secondary'], alignment=TA_CENTER,
|
|
279
|
-
spaceAfter=30,
|
|
280
|
-
),
|
|
281
|
-
'h1': ParagraphStyle(
|
|
282
|
-
'H1', fontName=FONT_BOLD, fontSize=20, leading=26,
|
|
283
|
-
textColor=COLORS['primary'], spaceBefore=28, spaceAfter=12,
|
|
284
|
-
borderWidth=0, borderPadding=0,
|
|
285
|
-
),
|
|
286
|
-
'h2': ParagraphStyle(
|
|
287
|
-
'H2', fontName=FONT_BOLD, fontSize=15, leading=20,
|
|
288
|
-
textColor=COLORS['secondary'], spaceBefore=20, spaceAfter=8,
|
|
289
|
-
),
|
|
290
|
-
'h3': ParagraphStyle(
|
|
291
|
-
'H3', fontName=FONT_BOLD, fontSize=12, leading=16,
|
|
292
|
-
textColor=COLORS['text'], spaceBefore=14, spaceAfter=6,
|
|
293
|
-
),
|
|
294
|
-
'body': ParagraphStyle(
|
|
295
|
-
'Body', fontName=FONT_BODY, fontSize=10.5, leading=15,
|
|
296
|
-
textColor=COLORS['text'], alignment=TA_JUSTIFY,
|
|
297
|
-
spaceBefore=2, spaceAfter=8,
|
|
298
|
-
),
|
|
299
|
-
'caption': ParagraphStyle(
|
|
300
|
-
'Caption', fontName=FONT_ITALIC, fontSize=9, leading=12,
|
|
301
|
-
textColor=COLORS['text_light'], alignment=TA_CENTER,
|
|
302
|
-
spaceBefore=4, spaceAfter=12,
|
|
303
|
-
),
|
|
304
|
-
'bullet': ParagraphStyle(
|
|
305
|
-
'Bullet', fontName=FONT_BODY, fontSize=10.5, leading=15,
|
|
306
|
-
textColor=COLORS['text'], leftIndent=24, bulletIndent=12,
|
|
307
|
-
spaceBefore=2, spaceAfter=4,
|
|
308
|
-
),
|
|
309
|
-
'code': ParagraphStyle(
|
|
310
|
-
'Code', fontName=FONT_MONO, fontSize=9, leading=13,
|
|
311
|
-
textColor=COLORS['text'], backColor=COLORS['bg_light'],
|
|
312
|
-
leftIndent=12, rightIndent=12,
|
|
313
|
-
spaceBefore=6, spaceAfter=6,
|
|
314
|
-
borderWidth=0.5, borderColor=COLORS['border'],
|
|
315
|
-
borderPadding=8,
|
|
316
|
-
),
|
|
317
|
-
'footer': ParagraphStyle(
|
|
318
|
-
'Footer', fontName=FONT_BODY, fontSize=8, leading=10,
|
|
319
|
-
textColor=COLORS['text_light'], alignment=TA_CENTER,
|
|
320
|
-
),
|
|
321
|
-
}
|
|
322
|
-
```
|
|
323
|
-
|
|
324
|
-
### Page Layout
|
|
325
|
-
|
|
326
|
-
```python
|
|
327
|
-
from reportlab.lib.pagesizes import A4
|
|
328
|
-
from reportlab.lib.units import cm, mm
|
|
329
|
-
|
|
330
|
-
PAGE_WIDTH, PAGE_HEIGHT = A4
|
|
331
|
-
MARGIN_LEFT = 2.5 * cm
|
|
332
|
-
MARGIN_RIGHT = 2.5 * cm
|
|
333
|
-
MARGIN_TOP = 2.5 * cm
|
|
334
|
-
MARGIN_BOTTOM = 2.5 * cm
|
|
335
|
-
CONTENT_WIDTH = PAGE_WIDTH - MARGIN_LEFT - MARGIN_RIGHT
|
|
336
|
-
```
|
|
337
|
-
|
|
338
|
-
## Document Structure Template
|
|
339
|
-
|
|
340
|
-
Every professional PDF MUST follow this structure:
|
|
341
|
-
|
|
342
|
-
### 1. Cover Page
|
|
343
|
-
|
|
344
|
-
```python
|
|
345
|
-
from reportlab.platypus import (
|
|
346
|
-
SimpleDocTemplate, Paragraph, Spacer, PageBreak,
|
|
347
|
-
Table, TableStyle, Image, HRFlowable
|
|
348
|
-
)
|
|
349
|
-
|
|
350
|
-
def build_cover(story, title, subtitle=None, author=None, date=None):
|
|
351
|
-
story.append(Spacer(1, 6 * cm))
|
|
352
|
-
|
|
353
|
-
story.append(Paragraph(title, STYLES['doc_title']))
|
|
354
|
-
|
|
355
|
-
story.append(Spacer(1, 0.5 * cm))
|
|
356
|
-
story.append(HRFlowable(
|
|
357
|
-
width='40%', thickness=2, color=COLORS['accent'],
|
|
358
|
-
spaceAfter=20, spaceBefore=10,
|
|
359
|
-
))
|
|
360
|
-
|
|
361
|
-
if subtitle:
|
|
362
|
-
story.append(Paragraph(subtitle, STYLES['doc_subtitle']))
|
|
363
|
-
|
|
364
|
-
story.append(Spacer(1, 3 * cm))
|
|
365
|
-
|
|
366
|
-
if author:
|
|
367
|
-
meta_style = ParagraphStyle(
|
|
368
|
-
'Meta', fontName=FONT_BODY, fontSize=11,
|
|
369
|
-
textColor=COLORS['text_light'], alignment=TA_CENTER,
|
|
370
|
-
spaceAfter=4,
|
|
371
|
-
)
|
|
372
|
-
story.append(Paragraph(author, meta_style))
|
|
373
|
-
|
|
374
|
-
if date:
|
|
375
|
-
date_style = ParagraphStyle(
|
|
376
|
-
'Date', fontName=FONT_BODY, fontSize=10,
|
|
377
|
-
textColor=COLORS['secondary'], alignment=TA_CENTER,
|
|
378
|
-
)
|
|
379
|
-
story.append(Paragraph(date, date_style))
|
|
380
|
-
|
|
381
|
-
story.append(PageBreak())
|
|
382
|
-
```
|
|
383
|
-
|
|
384
|
-
### 2. Header and Footer
|
|
385
|
-
|
|
386
|
-
```python
|
|
387
|
-
def header_footer(canvas_obj, doc):
|
|
388
|
-
canvas_obj.saveState()
|
|
389
|
-
|
|
390
|
-
# Header line
|
|
391
|
-
canvas_obj.setStrokeColor(COLORS['secondary'])
|
|
392
|
-
canvas_obj.setLineWidth(1.5)
|
|
393
|
-
y_header = PAGE_HEIGHT - 1.5 * cm
|
|
394
|
-
canvas_obj.line(MARGIN_LEFT, y_header, PAGE_WIDTH - MARGIN_RIGHT, y_header)
|
|
395
|
-
|
|
396
|
-
# Header text
|
|
397
|
-
canvas_obj.setFont(FONT_BODY, 8)
|
|
398
|
-
canvas_obj.setFillColor(COLORS['text_light'])
|
|
399
|
-
canvas_obj.drawString(MARGIN_LEFT, y_header + 4, doc.title or '')
|
|
400
|
-
|
|
401
|
-
# Footer line
|
|
402
|
-
y_footer = 1.2 * cm
|
|
403
|
-
canvas_obj.setStrokeColor(COLORS['border'])
|
|
404
|
-
canvas_obj.setLineWidth(0.5)
|
|
405
|
-
canvas_obj.line(MARGIN_LEFT, y_footer + 8, PAGE_WIDTH - MARGIN_RIGHT, y_footer + 8)
|
|
406
|
-
|
|
407
|
-
# Page number
|
|
408
|
-
canvas_obj.setFont(FONT_BODY, 8)
|
|
409
|
-
canvas_obj.setFillColor(COLORS['text_light'])
|
|
410
|
-
page_text = f"Page {doc.page}"
|
|
411
|
-
canvas_obj.drawCentredString(PAGE_WIDTH / 2, y_footer, page_text)
|
|
412
|
-
|
|
413
|
-
canvas_obj.restoreState()
|
|
414
|
-
```
|
|
415
|
-
|
|
416
|
-
### 3. Table of Contents
|
|
417
|
-
|
|
418
|
-
```python
|
|
419
|
-
def build_toc(story, sections):
|
|
420
|
-
story.append(Paragraph("Table of Contents", STYLES['h1']))
|
|
421
|
-
story.append(Spacer(1, 0.5 * cm))
|
|
422
|
-
|
|
423
|
-
toc_style = ParagraphStyle(
|
|
424
|
-
'TOCEntry', fontName=FONT_BODY, fontSize=11, leading=20,
|
|
425
|
-
textColor=COLORS['text'],
|
|
426
|
-
)
|
|
427
|
-
toc_bold = ParagraphStyle(
|
|
428
|
-
'TOCBold', fontName=FONT_BOLD, fontSize=11, leading=20,
|
|
429
|
-
textColor=COLORS['primary'],
|
|
430
|
-
)
|
|
431
|
-
|
|
432
|
-
for i, section in enumerate(sections, 1):
|
|
433
|
-
title = section['title']
|
|
434
|
-
page = section.get('page', '')
|
|
435
|
-
is_main = section.get('level', 1) == 1
|
|
436
|
-
|
|
437
|
-
style = toc_bold if is_main else toc_style
|
|
438
|
-
indent = 0 if is_main else 20
|
|
439
|
-
|
|
440
|
-
entry = Table(
|
|
441
|
-
[[Paragraph(f"{' ' * (indent // 4)}{i}. {title}" if is_main else f" {title}", style),
|
|
442
|
-
Paragraph(str(page), style)]],
|
|
443
|
-
colWidths=[CONTENT_WIDTH - 40, 40],
|
|
444
|
-
)
|
|
445
|
-
entry.setStyle(TableStyle([
|
|
446
|
-
('ALIGN', (1, 0), (1, 0), 'RIGHT'),
|
|
447
|
-
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
|
|
448
|
-
('LINEBELOW', (0, 0), (-1, -1), 0.5, COLORS['bg_light']),
|
|
449
|
-
('TOPPADDING', (0, 0), (-1, -1), 4),
|
|
450
|
-
('BOTTOMPADDING', (0, 0), (-1, -1), 4),
|
|
451
|
-
]))
|
|
452
|
-
story.append(entry)
|
|
453
|
-
|
|
454
|
-
story.append(PageBreak())
|
|
455
|
-
```
|
|
456
|
-
|
|
457
|
-
### 4. Section Headers with Accent Bar
|
|
458
|
-
|
|
459
|
-
```python
|
|
460
|
-
def add_section(story, number, title):
|
|
461
|
-
header_table = Table(
|
|
462
|
-
[[Paragraph(f"{number}.", ParagraphStyle(
|
|
463
|
-
'SNum', fontName=FONT_BOLD, fontSize=20,
|
|
464
|
-
textColor=COLORS['accent'],
|
|
465
|
-
)),
|
|
466
|
-
Paragraph(title, STYLES['h1'])]],
|
|
467
|
-
colWidths=[35, CONTENT_WIDTH - 35],
|
|
468
|
-
)
|
|
469
|
-
header_table.setStyle(TableStyle([
|
|
470
|
-
('VALIGN', (0, 0), (-1, -1), 'TOP'),
|
|
471
|
-
('TOPPADDING', (0, 0), (-1, -1), 0),
|
|
472
|
-
('BOTTOMPADDING', (0, 0), (-1, -1), 0),
|
|
473
|
-
]))
|
|
474
|
-
story.append(header_table)
|
|
475
|
-
|
|
476
|
-
story.append(HRFlowable(
|
|
477
|
-
width='100%', thickness=1, color=COLORS['secondary'],
|
|
478
|
-
spaceAfter=12,
|
|
479
|
-
))
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
### 5. Callout / Info Boxes
|
|
483
|
-
|
|
484
|
-
```python
|
|
485
|
-
def add_callout(story, title, text, box_type='info'):
|
|
486
|
-
bg = COLORS['bg_accent'] if box_type == 'info' else COLORS['bg_light']
|
|
487
|
-
border = COLORS['secondary'] if box_type == 'info' else COLORS['accent']
|
|
488
|
-
label = 'Information' if box_type == 'info' else 'Warning'
|
|
489
|
-
|
|
490
|
-
content = [
|
|
491
|
-
[Paragraph(
|
|
492
|
-
f"<b>{label} — {title}</b>",
|
|
493
|
-
ParagraphStyle('CalloutTitle', fontName=FONT_BOLD,
|
|
494
|
-
fontSize=10, textColor=COLORS['primary'],
|
|
495
|
-
spaceAfter=4)
|
|
496
|
-
)],
|
|
497
|
-
[Paragraph(
|
|
498
|
-
text,
|
|
499
|
-
ParagraphStyle('CalloutBody', fontName=FONT_BODY,
|
|
500
|
-
fontSize=9.5, leading=14,
|
|
501
|
-
textColor=COLORS['text'])
|
|
502
|
-
)],
|
|
503
|
-
]
|
|
504
|
-
|
|
505
|
-
table = Table(content, colWidths=[CONTENT_WIDTH - 20])
|
|
506
|
-
table.setStyle(TableStyle([
|
|
507
|
-
('BACKGROUND', (0, 0), (-1, -1), bg),
|
|
508
|
-
('BOX', (0, 0), (-1, -1), 1.5, border),
|
|
509
|
-
('LEFTPADDING', (0, 0), (-1, -1), 14),
|
|
510
|
-
('RIGHTPADDING', (0, 0), (-1, -1), 14),
|
|
511
|
-
('TOPPADDING', (0, 0), (0, 0), 10),
|
|
512
|
-
('BOTTOMPADDING', (-1, -1), (-1, -1), 10),
|
|
513
|
-
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
|
|
514
|
-
]))
|
|
515
|
-
story.append(Spacer(1, 8))
|
|
516
|
-
story.append(table)
|
|
517
|
-
story.append(Spacer(1, 8))
|
|
518
|
-
```
|
|
519
|
-
|
|
520
|
-
### 6. Professional Tables
|
|
521
|
-
|
|
522
|
-
```python
|
|
523
|
-
def add_table(story, headers, rows, col_widths=None):
|
|
524
|
-
data = [headers] + rows
|
|
525
|
-
|
|
526
|
-
if not col_widths:
|
|
527
|
-
col_widths = [CONTENT_WIDTH / len(headers)] * len(headers)
|
|
528
|
-
|
|
529
|
-
table = Table(data, colWidths=col_widths, repeatRows=1)
|
|
530
|
-
table.setStyle(TableStyle([
|
|
531
|
-
# Header
|
|
532
|
-
('BACKGROUND', (0, 0), (-1, 0), COLORS['primary']),
|
|
533
|
-
('TEXTCOLOR', (0, 0), (-1, 0), COLORS['white']),
|
|
534
|
-
('FONTNAME', (0, 0), (-1, 0), FONT_BOLD),
|
|
535
|
-
('FONTSIZE', (0, 0), (-1, 0), 10),
|
|
536
|
-
('BOTTOMPADDING', (0, 0), (-1, 0), 10),
|
|
537
|
-
('TOPPADDING', (0, 0), (-1, 0), 10),
|
|
538
|
-
|
|
539
|
-
# Body rows
|
|
540
|
-
('FONTNAME', (0, 1), (-1, -1), FONT_BODY),
|
|
541
|
-
('FONTSIZE', (0, 1), (-1, -1), 9.5),
|
|
542
|
-
('TEXTCOLOR', (0, 1), (-1, -1), COLORS['text']),
|
|
543
|
-
('TOPPADDING', (0, 1), (-1, -1), 7),
|
|
544
|
-
('BOTTOMPADDING', (0, 1), (-1, -1), 7),
|
|
545
|
-
|
|
546
|
-
# Alternating row colors
|
|
547
|
-
*[('BACKGROUND', (0, i), (-1, i), COLORS['bg_light'])
|
|
548
|
-
for i in range(1, len(data), 2)],
|
|
549
|
-
|
|
550
|
-
# Grid
|
|
551
|
-
('LINEBELOW', (0, 0), (-1, 0), 1.5, COLORS['secondary']),
|
|
552
|
-
('LINEBELOW', (0, 1), (-1, -2), 0.5, COLORS['border']),
|
|
553
|
-
('LINEBELOW', (0, -1), (-1, -1), 1, COLORS['secondary']),
|
|
554
|
-
|
|
555
|
-
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
|
|
556
|
-
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
|
|
557
|
-
('LEFTPADDING', (0, 0), (-1, -1), 10),
|
|
558
|
-
('RIGHTPADDING', (0, 0), (-1, -1), 10),
|
|
559
|
-
]))
|
|
560
|
-
story.append(table)
|
|
561
|
-
story.append(Spacer(1, 12))
|
|
562
|
-
```
|
|
563
|
-
|
|
564
|
-
### 7. Building the Document
|
|
565
|
-
|
|
566
|
-
```python
|
|
567
|
-
from datetime import date
|
|
568
|
-
|
|
569
|
-
doc = SimpleDocTemplate(
|
|
570
|
-
"output.pdf",
|
|
571
|
-
pagesize=A4,
|
|
572
|
-
leftMargin=MARGIN_LEFT,
|
|
573
|
-
rightMargin=MARGIN_RIGHT,
|
|
574
|
-
topMargin=MARGIN_TOP,
|
|
575
|
-
bottomMargin=MARGIN_BOTTOM,
|
|
576
|
-
title="Document Title",
|
|
577
|
-
author="BluMa",
|
|
578
|
-
)
|
|
579
|
-
|
|
580
|
-
story = []
|
|
581
|
-
|
|
582
|
-
build_cover(story, "Document Title", subtitle="A Professional Report",
|
|
583
|
-
author="Generated by BluMa", date=date.today().strftime('%B %Y'))
|
|
584
|
-
|
|
585
|
-
build_toc(story, [
|
|
586
|
-
{'title': 'Introduction', 'level': 1, 'page': 3},
|
|
587
|
-
{'title': 'Analysis', 'level': 1, 'page': 5},
|
|
588
|
-
])
|
|
589
|
-
|
|
590
|
-
add_section(story, 1, "Introduction")
|
|
591
|
-
story.append(Paragraph("Body text here...", STYLES['body']))
|
|
592
|
-
add_callout(story, "Key Insight", "Important information goes here.")
|
|
593
|
-
|
|
594
|
-
add_section(story, 2, "Analysis")
|
|
595
|
-
add_table(story,
|
|
596
|
-
['Metric', 'Value', 'Change'],
|
|
597
|
-
[['Revenue', '$1.2M', '+15%'], ['Users', '50K', '+22%']],
|
|
598
|
-
)
|
|
599
|
-
|
|
600
|
-
def cover_canvas(canvas_obj, doc):
|
|
601
|
-
"""Page 1 only: brand bar / rules. See create_report.py draw_cover_canvas."""
|
|
602
|
-
pass
|
|
603
|
-
|
|
604
|
-
# First page = cover art; later pages = header + footer
|
|
605
|
-
doc.build(story, onFirstPage=cover_canvas, onLaterPages=header_footer)
|
|
606
|
-
```
|
|
607
|
-
|
|
608
|
-
## Design Rules (MANDATORY)
|
|
609
|
-
|
|
610
|
-
1. **Never use default reportlab styles** — always create custom styles
|
|
611
|
-
2. **Font hierarchy**: Title 28pt > H1 20pt > H2 15pt > H3 12pt > Body 10.5pt
|
|
612
|
-
3. **Line height**: Always 1.4x font size minimum (e.g. 10.5pt font → 15pt leading)
|
|
613
|
-
4. **Margins**: Minimum 2.5cm on all sides
|
|
614
|
-
5. **Color**: Maximum 3-4 colors per document. Use the palette above
|
|
615
|
-
6. **Tables**: Always have header styling, alternating rows, proper padding
|
|
616
|
-
7. **Spacing**: Generous whitespace. Use `Spacer` between sections
|
|
617
|
-
8. **Cover page**: Every document with 3+ pages MUST have a cover page
|
|
618
|
-
9. **Headers/Footers**: Every multi-page document MUST have page numbers
|
|
619
|
-
10. **Body text**: use `Paragraph` + styles, never raw `drawString` for
|
|
620
|
-
paragraphs. **Exception:** minimal `drawString` in `onFirstPage` /
|
|
621
|
-
`onLaterPages` canvas callbacks for running title and page numbers only.
|
|
622
|
-
11. **Alignment**: Body text justified, titles centered, code left-aligned
|
|
623
|
-
12. **Callout boxes**: Use for key insights, warnings, important notes
|
|
624
|
-
13. **Section dividers**: Use `HRFlowable` or colored bars between major sections
|
|
625
|
-
14. **Subscripts/Superscripts**: Use `<sub>` and `<super>` tags, NEVER Unicode chars
|
|
626
|
-
|
|
627
|
-
## Reading & Extracting from PDFs
|
|
628
|
-
|
|
629
|
-
### Extract Text
|
|
630
|
-
```python
|
|
631
|
-
import pdfplumber
|
|
632
|
-
|
|
633
|
-
with pdfplumber.open("document.pdf") as pdf:
|
|
634
|
-
for page in pdf.pages:
|
|
635
|
-
print(page.extract_text())
|
|
636
|
-
```
|
|
637
|
-
|
|
638
|
-
### Extract Tables to DataFrame
|
|
639
|
-
```python
|
|
640
|
-
import pandas as pd
|
|
641
|
-
import pdfplumber
|
|
642
|
-
|
|
643
|
-
with pdfplumber.open("document.pdf") as pdf:
|
|
644
|
-
tables = []
|
|
645
|
-
for page in pdf.pages:
|
|
646
|
-
for table in page.extract_tables():
|
|
647
|
-
if table:
|
|
648
|
-
df = pd.DataFrame(table[1:], columns=table[0])
|
|
649
|
-
tables.append(df)
|
|
650
|
-
|
|
651
|
-
if tables:
|
|
652
|
-
combined = pd.concat(tables, ignore_index=True)
|
|
653
|
-
combined.to_excel("extracted.xlsx", index=False)
|
|
654
|
-
```
|
|
655
|
-
|
|
656
|
-
## Merge, Split, Protect
|
|
657
|
-
|
|
658
|
-
### Merge PDFs
|
|
659
|
-
```python
|
|
660
|
-
from pypdf import PdfWriter, PdfReader
|
|
661
|
-
|
|
662
|
-
writer = PdfWriter()
|
|
663
|
-
for f in ["doc1.pdf", "doc2.pdf"]:
|
|
664
|
-
for page in PdfReader(f).pages:
|
|
665
|
-
writer.add_page(page)
|
|
666
|
-
|
|
667
|
-
with open("merged.pdf", "wb") as out:
|
|
668
|
-
writer.write(out)
|
|
669
|
-
```
|
|
670
|
-
|
|
671
|
-
### Password Protection
|
|
672
|
-
```python
|
|
673
|
-
from pypdf import PdfReader, PdfWriter
|
|
674
|
-
|
|
675
|
-
reader = PdfReader("input.pdf")
|
|
676
|
-
writer = PdfWriter()
|
|
677
|
-
for page in reader.pages:
|
|
678
|
-
writer.add_page(page)
|
|
679
|
-
writer.encrypt("user_password", "owner_password")
|
|
680
|
-
|
|
681
|
-
with open("protected.pdf", "wb") as out:
|
|
682
|
-
writer.write(out)
|
|
683
|
-
```
|
|
684
|
-
|
|
685
|
-
## OCR (Scanned PDFs)
|
|
686
|
-
```python
|
|
687
|
-
import pytesseract
|
|
688
|
-
from pdf2image import convert_from_path
|
|
689
|
-
|
|
690
|
-
images = convert_from_path('scanned.pdf')
|
|
691
|
-
text = ""
|
|
692
|
-
for i, img in enumerate(images):
|
|
693
|
-
text += f"--- Page {i+1} ---\n"
|
|
694
|
-
text += pytesseract.image_to_string(img, lang="por+eng")
|
|
695
|
-
text += "\n\n"
|
|
696
|
-
```
|
|
697
|
-
|
|
698
|
-
## Quick Reference
|
|
699
|
-
|
|
700
|
-
| Task | Tool | Key API |
|
|
701
|
-
|------|------|---------|
|
|
702
|
-
| Create PDF | reportlab | `SimpleDocTemplate` + `Platypus` |
|
|
703
|
-
| Read text | pdfplumber | `page.extract_text()` |
|
|
704
|
-
| Read tables | pdfplumber | `page.extract_tables()` |
|
|
705
|
-
| Merge | pypdf | `PdfWriter.add_page()` |
|
|
706
|
-
| Split | pypdf | One page per `PdfWriter` |
|
|
707
|
-
| Protect | pypdf | `writer.encrypt()` |
|
|
708
|
-
| Watermark | pypdf | `page.merge_page()` |
|
|
709
|
-
| OCR | pytesseract | `image_to_string()` |
|
|
710
|
-
| Forms | pypdf | See references/FORMS.md |
|
|
711
|
-
| CLI merge | qpdf | `qpdf --empty --pages` |
|
|
712
|
-
|
|
713
|
-
## Available References
|
|
714
|
-
|
|
715
|
-
- REFERENCE.md: Advanced reportlab features, JavaScript pdf-lib, CLI tools
|
|
716
|
-
- FORMS.md: Filling and creating PDF forms
|
|
717
|
-
|
|
718
|
-
## Available Scripts
|
|
719
|
-
|
|
720
|
-
- **create_report.py** — default: demo PDF; **production:** `--from-json FILE`
|
|
721
|
-
- Before writing JSON, follow **“JSON quality”** (this file) so content matches
|
|
722
|
-
the clean template — schema alone is not enough.
|
|
723
|
-
- Schema (top-level keys): `title`, `subtitle?`, `author?`, `audience?`
|
|
724
|
-
(`technical` | `mixed` | `general`), `document_type?`, `letterhead?`,
|
|
725
|
-
`layout?`, `page_break_per_section?` (override do preset), `sections[]`.
|
|
726
|
-
- Each section: `num` (int), `title` (str), `blocks` (array).
|
|
727
|
-
- Each block: `type` is one of:
|
|
728
|
-
- `paragraph` — `{ "type": "paragraph", "text": "..." }` (use `\n` for line breaks)
|
|
729
|
-
- `h2` — `{ "type": "h2", "text": "..." }`
|
|
730
|
-
- `callout` — `{ "type": "callout", "title": "...", "text": "...", "variant": "info"|"warning" }`
|
|
731
|
-
- `bullets` — `{ "type": "bullets", "items": ["...", "..."] }`
|
|
732
|
-
- `table` — `{ "type": "table", "headers": [...], "rows": [[...],...], "col_widths": null or [pt,...] }`
|
|
733
|
-
- `spacer` — `{ "type": "spacer", "pt": 12 }`
|
|
734
|
-
- Plain text in JSON is XML-escaped automatically; do not embed ReportLab HTML
|
|
735
|
-
unless you generate JSON from trusted code that already escapes markup.
|
|
736
|
-
- merge_pdfs.py: Merge multiple PDFs into one
|