-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_generator.py
More file actions
745 lines (616 loc) · 24.7 KB
/
Copy pathpdf_generator.py
File metadata and controls
745 lines (616 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# PDF Style Engine v2.0
# (c) 2025 Claudia Ortega
# Licensed under CC BY-NC-ND 4.0
# https://creativecommons.org/licenses/by-nc-nd/4.0/
"""
pdf_generator.py
================
A modular PDF generation engine with two fully independent visual styles:
- "professional": Clean, minimalistic corporate layout
- "cyber": Neon/cyberpunk code-aesthetic layout
Entry point
-----------
generate_pdf(style, data, output_path)
Supported styles
----------------
"professional" → ProfessionalStyle
"cyber" → CyberStyle
Data dict keys (all optional unless noted)
------------------------------------------
title str – Main document title
subtitle str – Secondary headline
date str – Date string shown in header
reference str – Reference / document ID
company str – Company or author name
logo_path str – Absolute path to a PNG logo (professional only)
contact str – Footer contact line
sections list – [{"heading": str, "body": str}, ...]
table dict – {"headers": [...], "rows": [[...], ...]}
ascii_art str – Pre-formatted ASCII block (cyber only)
hash_id str – Hash-like ID for cyber footer
"""
from __future__ import annotations
import hashlib
import math
import os
import time
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Any
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.platypus import (
BaseDocTemplate,
Frame,
PageTemplate,
Paragraph,
Spacer,
Table,
TableStyle,
)
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
W, H = A4 # 595.27 x 841.89 pts
def _hex(h: str) -> colors.HexColor:
return colors.HexColor(h)
def _safe(data: dict, key: str, default: Any = None) -> Any:
"""Return data[key] only when it's a non-empty string (or truthy value)."""
v = data.get(key, default)
if isinstance(v, str):
return v.strip() or default
return v
# ---------------------------------------------------------------------------
# Abstract base style
# ---------------------------------------------------------------------------
class BaseStyle(ABC):
"""Strategy interface. Each concrete style handles its own canvas drawing."""
def __init__(self, data: dict):
self.data = data
@abstractmethod
def build(self, output_path: str) -> None:
...
# ===========================================================================
# 1. PROFESSIONAL / MINIMALISTIC STYLE
# ===========================================================================
class ProfessionalStyle(BaseStyle):
"""
Clean, modern layout.
Palette: #1A1A1A #4A4A4A #EAEAEA #007ACC
"""
# --- palette ---
C_DARK = _hex("#1A1A1A")
C_MID = _hex("#4A4A4A")
C_LIGHT = _hex("#EAEAEA")
C_ACCENT = _hex("#007ACC")
C_WHITE = colors.white
C_ALT_ROW = _hex("#F5F8FB")
# --- layout ---
MARGIN_X = 18 * mm
MARGIN_Y = 16 * mm
HEADER_H = 28 * mm
FOOTER_H = 14 * mm
def build(self, output_path: str) -> None:
c = canvas.Canvas(output_path, pagesize=A4)
c.setTitle(_safe(self.data, "title", "Document"))
page_num = [0]
def draw_page(c: canvas.Canvas) -> None:
page_num[0] += 1
self._draw_header(c)
self._draw_footer(c, page_num[0])
# ---- build content area ----
content_y = H - self.HEADER_H - self.MARGIN_Y
draw_page(c)
content_y = self._draw_body(c, content_y, draw_page)
c.save()
# ------------------------------------------------------------------
def _draw_header(self, c: canvas.Canvas) -> None:
mx, hy = self.MARGIN_X, self.HEADER_H
# Accent bar at very top
c.setFillColor(self.C_ACCENT)
c.rect(0, H - 6, W, 6, fill=1, stroke=0)
# Logo
logo = _safe(self.data, "logo_path")
logo_right = self.MARGIN_X # track where logo ends (for title offset)
if logo and os.path.isfile(logo):
try:
c.drawImage(logo, mx, H - hy + 4 * mm,
width=22 * mm, height=14 * mm,
preserveAspectRatio=True, mask="auto")
logo_right = mx + 26 * mm
except Exception:
pass
# Title
title = _safe(self.data, "title")
if title:
c.setFont("Helvetica-Bold", 18)
c.setFillColor(self.C_DARK)
c.drawString(logo_right, H - 14 * mm, title)
# Subtitle
subtitle = _safe(self.data, "subtitle")
if subtitle:
c.setFont("Helvetica", 12)
c.setFillColor(self.C_MID)
c.drawString(logo_right, H - 20 * mm, subtitle)
# Right-side meta: date + reference
right_x = W - self.MARGIN_X
meta_y = H - 13 * mm
date_str = _safe(self.data, "date")
ref_str = _safe(self.data, "reference")
if date_str:
c.setFont("Helvetica", 9)
c.setFillColor(self.C_MID)
c.drawRightString(right_x, meta_y, date_str)
meta_y -= 5 * mm
if ref_str:
c.setFont("Helvetica", 9)
c.setFillColor(self.C_MID)
c.drawRightString(right_x, meta_y, f"Ref: {ref_str}")
# Separator line
c.setStrokeColor(self.C_LIGHT)
c.setLineWidth(1.2)
c.line(self.MARGIN_X, H - hy, W - self.MARGIN_X, H - hy)
# ------------------------------------------------------------------
def _draw_footer(self, c: canvas.Canvas, page_num: int) -> None:
fy = self.FOOTER_H
mx = self.MARGIN_X
# Top rule
c.setStrokeColor(self.C_LIGHT)
c.setLineWidth(0.8)
c.line(mx, fy, W - mx, fy)
# Page number
c.setFont("Helvetica", 8)
c.setFillColor(self.C_MID)
c.drawCentredString(W / 2, fy - 5 * mm, f"Page {page_num}")
# Contact info left
contact = _safe(self.data, "contact")
if contact:
c.setFont("Helvetica", 8)
c.setFillColor(self.C_MID)
c.drawString(mx, fy - 5 * mm, contact)
# Company right
company = _safe(self.data, "company")
if company:
c.setFont("Helvetica-Bold", 8)
c.setFillColor(self.C_ACCENT)
c.drawRightString(W - mx, fy - 5 * mm, company)
# ------------------------------------------------------------------
def _draw_body(self, c: canvas.Canvas, y: float, new_page_cb) -> float:
mx = self.MARGIN_X
right = W - self.MARGIN_X
body_w = right - mx
min_y = self.FOOTER_H + 8 * mm
def check_space(needed: float) -> float:
nonlocal y
if y - needed < min_y:
c.showPage()
new_page_cb(c)
y = H - self.HEADER_H - self.MARGIN_Y
return y
# ---- Sections ----
sections = _safe(self.data, "sections", [])
for sec in sections:
heading = (sec.get("heading") or "").strip()
body = (sec.get("body") or "").strip()
if heading:
y = check_space(14 * mm)
c.setFont("Helvetica-Bold", 13)
c.setFillColor(self.C_ACCENT)
c.drawString(mx, y, heading)
y -= 3 * mm
# Thin rule under heading
c.setStrokeColor(self.C_LIGHT)
c.setLineWidth(0.8)
c.line(mx, y, right, y)
y -= 5 * mm
if body:
# Word-wrap body text manually
c.setFont("Helvetica", 10)
c.setFillColor(self.C_DARK)
for line in self._wrap_text(body, "Helvetica", 10, body_w):
y = check_space(5 * mm)
c.drawString(mx, y, line)
y -= 4.5 * mm
y -= 4 * mm
# ---- Table ----
table_data_raw = _safe(self.data, "table")
if table_data_raw:
headers = table_data_raw.get("headers", [])
rows = table_data_raw.get("rows", [])
if headers and rows:
y = check_space(20 * mm)
y = self._draw_table(c, headers, rows, mx, y, body_w, min_y,
new_page_cb)
return y
# ------------------------------------------------------------------
def _draw_table(self, c, headers, rows, x, y, width, min_y, new_page_cb):
col_n = len(headers)
col_w = width / col_n
row_h = 7 * mm
pad_x = 3 * mm
all_rows = [headers] + rows
for i, row in enumerate(all_rows):
if y - row_h < min_y:
c.showPage()
new_page_cb(c)
y = H - self.HEADER_H - self.MARGIN_Y
is_header = (i == 0)
is_alt = (not is_header) and (i % 2 == 0)
# Row background
if is_header:
c.setFillColor(self.C_DARK)
elif is_alt:
c.setFillColor(self.C_ALT_ROW)
else:
c.setFillColor(self.C_WHITE)
c.rect(x, y - row_h, width, row_h, fill=1, stroke=0)
# Cell borders
c.setStrokeColor(self.C_LIGHT)
c.setLineWidth(0.5)
c.rect(x, y - row_h, width, row_h, fill=0, stroke=1)
# Text
for j, cell in enumerate(row[:col_n]):
cx = x + j * col_w + pad_x
if is_header:
c.setFont("Helvetica-Bold", 9)
c.setFillColor(self.C_WHITE)
else:
c.setFont("Helvetica", 9)
c.setFillColor(self.C_DARK)
c.drawString(cx, y - row_h + 2 * mm, str(cell))
y -= row_h
return y - 4 * mm
# ------------------------------------------------------------------
@staticmethod
def _wrap_text(text: str, font: str, size: float, max_width: float) -> list[str]:
"""Simple greedy word-wrapper using ReportLab string width."""
from reportlab.pdfbase.pdfmetrics import stringWidth
words = text.split()
lines = []
current = ""
for word in words:
test = (current + " " + word).strip()
if stringWidth(test, font, size) <= max_width:
current = test
else:
if current:
lines.append(current)
current = word
if current:
lines.append(current)
return lines
# ===========================================================================
# 2. DARK NEON MINIMAL STYLE (formerly "Cyber")
# ===========================================================================
class CyberStyle(BaseStyle):
"""
Dark, modern, minimalistic with deliberate neon accents.
Palette: deep charcoal background, off-white text, neon green
primary accent, electric violet secondary, warm amber highlight.
No grids, no glitch, no clutter — just clean geometry and light.
"""
# --- palette ---
C_BG = _hex("#0D0D0D") # near-black background
C_SURFACE = _hex("#161616") # card / panel surface
C_BORDER = _hex("#242424") # subtle separator
C_TEXT = _hex("#E8E8E8") # primary text
C_MUTED = _hex("#606060") # secondary / meta text
C_NEON = _hex("#AAFF4D") # neon green — primary accent
C_VIOLET = _hex("#8B5CF6") # electric violet — secondary accent
C_AMBER = _hex("#F59E0B") # warm amber — highlight / warning
C_WHITE = colors.white
# --- layout ---
MARGIN_X = 20 * mm
MARGIN_Y = 14 * mm
HEADER_H = 32 * mm
FOOTER_H = 13 * mm
SANS = "Helvetica-Bold"
SANS_REG = "Helvetica"
MONO = "Courier-Bold"
MONO_REG = "Courier"
def build(self, output_path: str) -> None:
c = canvas.Canvas(output_path, pagesize=A4)
c.setTitle(_safe(self.data, "title", "Document"))
page_num = [0]
def draw_page(c: canvas.Canvas) -> None:
page_num[0] += 1
self._draw_background(c)
self._draw_header(c)
self._draw_footer(c, page_num[0])
draw_page(c)
self._draw_body(c, draw_page)
c.save()
# ------------------------------------------------------------------
def _draw_background(self, c: canvas.Canvas) -> None:
# Full-page dark fill
c.setFillColor(self.C_BG)
c.rect(0, 0, W, H, fill=1, stroke=0)
# Very faint horizontal scan-lines (4 pt gap) — subtle texture
c.setStrokeColor(self.C_SURFACE)
c.setLineWidth(0.5)
y = 0
while y <= H:
c.line(0, y, W, y)
y += 4
# Left neon accent strip — slim vertical bar
c.setFillColor(self.C_NEON)
c.rect(0, 0, 3, H, fill=1, stroke=0)
# Top-right corner decoration: two concentric quarter-circle arcs
cx_arc, cy_arc = W, H
c.setStrokeColor(self.C_VIOLET)
c.setLineWidth(0.6)
c.setStrokeAlpha(0.35)
c.arc(cx_arc - 60, cy_arc - 60, cx_arc + 60, cy_arc + 60, startAng=180, extent=90)
c.arc(cx_arc - 90, cy_arc - 90, cx_arc + 90, cy_arc + 90, startAng=180, extent=90)
c.setStrokeAlpha(1.0)
# Bottom-left mirrored decoration
c.setStrokeColor(self.C_NEON)
c.setLineWidth(0.4)
c.setStrokeAlpha(0.20)
c.arc(-50, -50, 50, 50, startAng=0, extent=90)
c.arc(-80, -80, 80, 80, startAng=0, extent=90)
c.setStrokeAlpha(1.0)
# ------------------------------------------------------------------
def _draw_header(self, c: canvas.Canvas) -> None:
mx = self.MARGIN_X
hy = self.HEADER_H
# Header surface panel
c.setFillColor(self.C_SURFACE)
c.rect(0, H - hy, W, hy, fill=1, stroke=0)
# Left accent re-draw on top of panel (keep it visible)
c.setFillColor(self.C_NEON)
c.rect(0, H - hy, 3, hy, fill=1, stroke=0)
# Neon dot marker before title
dot_x = mx + 2
dot_y = H - 16 * mm
c.setFillColor(self.C_NEON)
c.circle(dot_x, dot_y + 1.5, 2.8, fill=1, stroke=0)
# Title — clean sans-serif, white, generous size
title = _safe(self.data, "title", "UNTITLED")
c.setFont(self.SANS, 20)
c.setFillColor(self.C_TEXT)
c.drawString(dot_x + 7, dot_y, title)
# Subtitle — muted, smaller, below title
subtitle = _safe(self.data, "subtitle")
if subtitle:
c.setFont(self.SANS_REG, 10)
c.setFillColor(self.C_MUTED)
c.drawString(dot_x + 7, dot_y - 6 * mm, subtitle)
# Right-side meta block — date + reference stacked
right_x = W - mx
meta_y = H - 10 * mm
date_str = _safe(self.data, "date", datetime.now().strftime("%Y-%m-%d"))
ref_str = _safe(self.data, "reference")
c.setFont(self.MONO_REG, 8)
c.setFillColor(self.C_NEON)
c.drawRightString(right_x, meta_y, date_str)
if ref_str:
c.setFillColor(self.C_MUTED)
c.drawRightString(right_x, meta_y - 4.5 * mm, ref_str)
# Separator — single pixel-thin line in neon
sep_y = H - hy + 0.5
c.setStrokeColor(self.C_NEON)
c.setLineWidth(0.8)
c.line(0, sep_y, W, sep_y)
# ------------------------------------------------------------------
def _draw_footer(self, c: canvas.Canvas, page_num: int) -> None:
mx = self.MARGIN_X
fy = self.FOOTER_H
# Footer surface
c.setFillColor(self.C_SURFACE)
c.rect(0, 0, W, fy, fill=1, stroke=0)
# Left accent strip in footer
c.setFillColor(self.C_NEON)
c.rect(0, 0, 3, fy, fill=1, stroke=0)
# Separator top
c.setStrokeColor(self.C_BORDER)
c.setLineWidth(0.6)
c.line(mx, fy, W - mx, fy)
# Left: generated-by label
c.setFont(self.MONO_REG, 7)
c.setFillColor(self.C_MUTED)
c.drawString(mx, fy / 2 - 1.5, "PDF ENGINE · DARK NEON STYLE")
# Centre: page indicator with neon dot decoration
centre_text = f"{page_num:02d}"
c.setFont(self.SANS, 8)
c.setFillColor(self.C_TEXT)
c.drawCentredString(W / 2, fy / 2 - 1.5, centre_text)
# Right: hash / id
hash_id = _safe(self.data, "hash_id")
if not hash_id:
raw = _safe(self.data, "title", "PDF") + str(page_num)
hash_id = hashlib.sha256(raw.encode()).hexdigest()[:12].upper()
c.setFont(self.MONO_REG, 7)
c.setFillColor(self.C_VIOLET)
c.drawRightString(W - mx, fy / 2 - 1.5, hash_id)
# ------------------------------------------------------------------
def _draw_body(self, c: canvas.Canvas, new_page_cb) -> None:
mx = self.MARGIN_X
right = W - self.MARGIN_X
body_w = right - mx
y = H - self.HEADER_H - self.MARGIN_Y
min_y = self.FOOTER_H + 10 * mm
def check_space(needed: float) -> float:
nonlocal y
if y - needed < min_y:
c.showPage()
new_page_cb(c)
y = H - self.HEADER_H - self.MARGIN_Y
return y
# ---- ASCII Art block ----
ascii_art = _safe(self.data, "ascii_art")
if ascii_art:
lines = ascii_art.splitlines()
line_h = 3.8 * mm
pad = 5 * mm
panel_h = len(lines) * line_h + pad * 2
y = check_space(panel_h + 4 * mm)
# Panel: surface background with neon left border
c.setFillColor(self.C_SURFACE)
c.rect(mx, y - panel_h, body_w, panel_h, fill=1, stroke=0)
c.setFillColor(self.C_NEON)
c.rect(mx, y - panel_h, 2.5, panel_h, fill=1, stroke=0)
ty = y - pad
for line in lines:
c.setFont(self.MONO_REG, 7.5)
c.setFillColor(self.C_NEON)
c.drawString(mx + 6 * mm, ty, line)
ty -= line_h
y -= panel_h + 6 * mm
# ---- Sections ----
sections = _safe(self.data, "sections", [])
for sec_idx, sec in enumerate(sections):
heading = (sec.get("heading") or "").strip()
body = (sec.get("body") or "").strip()
if heading:
y = check_space(14 * mm)
# Section index badge (01, 02 …)
badge = f"{sec_idx + 1:02d}"
c.setFont(self.MONO, 7)
c.setFillColor(self.C_NEON)
c.drawString(mx, y, badge)
# Heading text — white, bold, slightly indented
c.setFont(self.SANS, 12)
c.setFillColor(self.C_TEXT)
c.drawString(mx + 8 * mm, y, heading.upper())
y -= 4 * mm
# Full-width thin rule, neon left segment + muted rest
neon_w = 12 * mm
c.setStrokeColor(self.C_NEON)
c.setLineWidth(1.0)
c.line(mx, y, mx + neon_w, y)
c.setStrokeColor(self.C_BORDER)
c.setLineWidth(0.5)
c.line(mx + neon_w, y, right, y)
y -= 5 * mm
if body:
wrapped = self._wrap_text(body, self.SANS_REG, 9.5, body_w - 4 * mm)
needed = len(wrapped) * 5 * mm + 4 * mm
y = check_space(needed)
c.setFont(self.SANS_REG, 9.5)
c.setFillColor(self.C_TEXT)
for line in wrapped:
y = check_space(5 * mm)
c.drawString(mx + 2 * mm, y, line)
y -= 5 * mm
y -= 4 * mm # breathing room between sections
# ---- Table ----
table_raw = _safe(self.data, "table")
if table_raw:
headers = table_raw.get("headers", [])
rows = table_raw.get("rows", [])
if headers and rows:
y = check_space(20 * mm)
y = self._draw_dark_table(c, headers, rows, mx, y, body_w,
min_y, new_page_cb)
# ------------------------------------------------------------------
def _draw_dark_table(self, c, headers, rows, x, y, width, min_y, new_page_cb):
col_n = len(headers)
col_w = width / col_n
row_h = 7.5 * mm
pad_x = 3.5 * mm
all_rows = [headers] + rows
for i, row in enumerate(all_rows):
if y - row_h < min_y:
c.showPage()
new_page_cb(c)
y = H - self.HEADER_H - self.MARGIN_Y
is_header = (i == 0)
is_alt = (not is_header) and (i % 2 == 0)
# Row fill
if is_header:
c.setFillColor(self.C_SURFACE)
elif is_alt:
c.setFillColor(_hex("#121212"))
else:
c.setFillColor(self.C_BG)
c.rect(x, y - row_h, width, row_h, fill=1, stroke=0)
# Bottom border only — cleaner than full box
c.setStrokeColor(self.C_BORDER)
c.setLineWidth(0.4)
c.line(x, y - row_h, x + width, y - row_h)
# Header: neon accent bar on top
if is_header:
c.setStrokeColor(self.C_NEON)
c.setLineWidth(1.2)
c.line(x, y, x + width, y)
for j, cell in enumerate(row[:col_n]):
cx = x + j * col_w + pad_x
ty = y - row_h + 2.5 * mm
if is_header:
c.setFont(self.SANS, 7.5)
c.setFillColor(self.C_NEON)
elif j == 0:
# First column — slightly highlighted
c.setFont(self.SANS_REG, 8)
c.setFillColor(self.C_TEXT)
else:
c.setFont(self.SANS_REG, 8)
c.setFillColor(self.C_MUTED)
# Amber highlight for cells containing "CRITICAL" or "PWNED"
cell_str = str(cell)
if not is_header and any(
kw in cell_str.upper()
for kw in ("CRITICAL", "PWNED", "EXPLOITED", "HIGH")
):
c.setFillColor(self.C_AMBER)
c.drawString(cx, ty, cell_str)
# Vertical column divider (very subtle)
if j < col_n - 1:
c.setStrokeColor(self.C_BORDER)
c.setLineWidth(0.3)
c.line(x + (j + 1) * col_w, y - row_h, x + (j + 1) * col_w, y)
y -= row_h
return y - 5 * mm
# ------------------------------------------------------------------
@staticmethod
def _wrap_text(text: str, font: str, size: float, max_width: float) -> list[str]:
from reportlab.pdfbase.pdfmetrics import stringWidth
words = text.split()
lines = []
current = ""
for word in words:
test = (current + " " + word).strip()
if stringWidth(test, font, size) <= max_width:
current = test
else:
if current:
lines.append(current)
current = word
if current:
lines.append(current)
return lines
# ===========================================================================
# Registry + public entry point
# ===========================================================================
_STYLE_REGISTRY: dict[str, type[BaseStyle]] = {
"professional": ProfessionalStyle,
"cyber": CyberStyle,
}
def register_style(name: str, cls: type[BaseStyle]) -> None:
"""Register a custom style class under a given name."""
_STYLE_REGISTRY[name] = cls
def generate_pdf(style: str, data: dict, output_path: str) -> str:
"""
Generate a PDF document.
Parameters
----------
style : "professional" | "cyber" (or any registered custom style)
data : dict of content fields (see module docstring)
output_path : destination file path (.pdf)
Returns
-------
Absolute path of the written PDF.
"""
style_key = style.lower().strip()
if style_key not in _STYLE_REGISTRY:
raise ValueError(
f"Unknown style '{style}'. Available: {list(_STYLE_REGISTRY)}"
)
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
renderer = _STYLE_REGISTRY[style_key](data)
renderer.build(output_path)
return os.path.abspath(output_path)