"""
Builds the branded PDF sent by both calculator flows ("email me a copy"
and the inline "let's talk" contact form) — one shared template, per
CLAUDE_CALCULATOR.md §6, driven entirely by whatever the frontend sends
(title, summary text, result label/value pairs, footnote, the proactive
Q&A). This module knows nothing about the calculator's own business logic
— the weighted-rate model, tier sizing, recovery percentages, etc. all
stay client-side and untouched (CLAUDE_CALCULATOR.md §8's explicit rule).
It only ever renders numbers/labels it's handed, so there is no
calculation logic to keep in sync between frontend and backend.
Data flow:
payload dict (see routes/calculator.py's _extract_shared_fields) →
fpdf2 document built section by section (header, title, summary,
results grid, proactive Q&A, footnote, footer CTA) → PDF bytes returned
"""
import re
from pathlib import Path
from fpdf import FPDF
from fpdf.enums import XPos, YPos
NAVY = (10, 20, 32)
ACCENT = (159, 232, 56)
INK = (13, 21, 38)
MUTED = (107, 122, 153)
# Same "B" mark used in the site's own nav (index.html's inline base64
# logo) — a full-resolution copy lives alongside this service so the PDF
# header doesn't depend on decoding it out of the frontend HTML.
_LOGO_PATH = Path(__file__).resolve().parent.parent / "assets" / "logo.png"
_LOGO_ASPECT = 1391 / 1980 # width / height of assets/logo.png
# fpdf2's multi_cell() with w=0 defaults to new_x=XPos.RIGHT — leaving the
# cursor at the RIGHT edge, not the left margin, after it finishes. Every
# block-level multi_cell() call below passes this explicitly rather than
# relying on a following ln() call to fix the position; two back-to-back
# multi_cell() calls with no reset in between (found live: the proactive
# Q&A pair, and the closing "Ready to talk?" heading + paragraph) computed
# their available width from that stale near-zero right-edge x position
# and raised FPDFException("Not enough horizontal space to render a
# single character") — reproduced and confirmed via isolated testing
# before this fix.
_BLOCK = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
# The built-in "Helvetica" core font only supports latin-1, not full
# Unicode — but the calculator's own copy (and any free text a visitor
# types into the proactive-answer textarea or the org/sector fields) uses
# em dashes, curly quotes, and arrows routinely. A real "email me a copy"
# request crashed generation outright with FPDFUnicodeEncodingException
# because its summary text contained a single em dash. First swap the
# specific characters this project's copy actually uses for ASCII
# equivalents so they still render as intended; anything still outside
# latin-1 after that (an accented name, an emoji someone typed) is
# replaced with "?" by the final encode rather than crashing the whole PDF.
_UNICODE_REPLACEMENTS = {
"—": "-", "–": "-", # em dash, en dash
"‘": "'", "’": "'", # curly single quotes
"“": '"', "”": '"', # curly double quotes
"…": "...", # ellipsis
"→": "->", # arrow
" ": " ", # non-breaking space
}
def _sanitize_text(value) -> str:
"""
Makes any dynamic string safe for fpdf2's latin-1-only core font.
Data flow:
raw value (may be None, or contain Unicode punctuation) →
known Unicode punctuation swapped for ASCII equivalents →
anything still outside latin-1 replaced with "?" → safe string
"""
text = "" if value is None else str(value)
for char, replacement in _UNICODE_REPLACEMENTS.items():
text = text.replace(char, replacement)
return text.encode("latin-1", errors="replace").decode("latin-1")
_STRONG_TAG_RE = re.compile(r"?strong>")
def _write_rich_text(pdf: FPDF, html_text: str, line_height: float, base_size: int) -> None:
"""
Writes a paragraph that may contain ... spans as real
bold runs, instead of printing the literal tag characters.
Data flow:
HTML string (calculator.js builds e-summary/o-summary with
innerHTML, so its tags survive into summary_text exactly
as typed — a visitor's downloaded PDF showed the literal
"" text because it was being handed straight to
multi_cell(), which only ever prints plain text) → split on the
/ boundary → each segment written with bold or
regular font, alternating → cursor moved to the next line
"""
pdf.set_font("Helvetica", "", base_size)
segments = _STRONG_TAG_RE.split(html_text)
for i, segment in enumerate(segments):
clean = _sanitize_text(segment)
if not clean:
continue
pdf.set_font("Helvetica", "B" if i % 2 == 1 else "", base_size)
pdf.write(line_height, clean)
pdf.set_font("Helvetica", "", base_size)
pdf.ln(line_height)
class _CalculatorPDF(FPDF):
def header(self):
self.set_fill_color(*NAVY)
self.rect(0, 0, self.w, 28, style="F")
text = "Bettersight Intelligence"
self.set_font("Helvetica", "B", 16)
text_w = self.get_string_width(text)
icon_h = 9.0
icon_w = icon_h * _LOGO_ASPECT
gap = 3.0
start_x = (self.w - (icon_w + gap + text_w)) / 2
if _LOGO_PATH.exists():
self.image(str(_LOGO_PATH), x=start_x, y=(28 - icon_h) / 2, h=icon_h)
self.set_xy(start_x + icon_w + gap, 9)
self.set_text_color(*ACCENT)
self.cell(text_w + 2, 10, text)
self.ln(20)
def footer(self):
self.set_y(-18)
self.set_font("Helvetica", "", 8)
self.set_text_color(*MUTED)
self.cell(0, 8, "Generated by the Bettersight Intelligence self-assessment tool", align="C")
def build_pdf(payload: dict) -> bytes:
"""
Renders one PDF from an already-computed results payload.
Data flow:
payload → title + summary paragraph → a 2-column grid of the
result label/value pairs exactly as shown on screen → the
proactive question/answer, if given → the basis footnote in small
print (methodology transparency has to survive into the PDF, not
just live on the page) → a closing "ready to talk?" CTA line
→ PDF bytes
"""
pdf = _CalculatorPDF(format="A4")
pdf.set_auto_page_break(auto=True, margin=24)
pdf.add_page()
pdf.set_text_color(*INK)
pdf.set_font("Helvetica", "B", 18)
pdf.multi_cell(0, 9, _sanitize_text(payload.get("title") or "Your Results"), **_BLOCK)
pdf.ln(2)
summary = payload.get("summary_text") or ""
if summary:
pdf.set_text_color(*INK)
pdf.set_xy(pdf.l_margin, pdf.get_y())
_write_rich_text(pdf, summary, line_height=6.5, base_size=11)
pdf.ln(4)
results = payload.get("results") or []
if results:
col_width = (pdf.w - pdf.l_margin - pdf.r_margin - 8) / 2
for i in range(0, len(results), 2):
row = results[i:i + 2]
y_start = pdf.get_y()
max_h = 0.0
for j, cell in enumerate(row):
x = pdf.l_margin + j * (col_width + 8)
pdf.set_xy(x, y_start)
pdf.set_font("Helvetica", "", 9)
pdf.set_text_color(*MUTED)
pdf.multi_cell(col_width, 5, _sanitize_text(cell.get("label", "")).upper())
pdf.set_xy(x, pdf.get_y())
pdf.set_font("Helvetica", "B", 15)
pdf.set_text_color(*INK)
pdf.multi_cell(col_width, 7, _sanitize_text(cell.get("value", "")))
max_h = max(max_h, pdf.get_y() - y_start)
pdf.set_xy(pdf.l_margin, y_start + max_h + 6)
pdf.ln(4)
proactive_answer = _sanitize_text(payload.get("proactive_answer") or "")
if proactive_answer:
proactive_question = _sanitize_text(payload.get("proactive_question") or "")
if proactive_question:
pdf.set_font("Helvetica", "B", 10)
pdf.set_text_color(*INK)
pdf.multi_cell(0, 6, proactive_question, **_BLOCK)
pdf.set_font("Helvetica", "", 10)
pdf.set_text_color(60, 60, 60)
pdf.multi_cell(0, 6, proactive_answer, **_BLOCK)
pdf.ln(4)
footnote = _sanitize_text(payload.get("basis_footnote") or "")
if footnote:
pdf.set_font("Helvetica", "", 8)
pdf.set_text_color(*MUTED)
pdf.multi_cell(0, 4.5, footnote, **_BLOCK)
pdf.ln(6)
pdf.set_draw_color(*ACCENT)
pdf.set_line_width(0.6)
pdf.line(pdf.l_margin, pdf.get_y(), pdf.w - pdf.r_margin, pdf.get_y())
pdf.ln(6)
pdf.set_font("Helvetica", "B", 12)
pdf.set_text_color(*INK)
pdf.multi_cell(0, 7, "Ready to talk?", **_BLOCK)
pdf.set_font("Helvetica", "", 10)
pdf.set_text_color(60, 60, 60)
pdf.multi_cell(0, 6, "Reply directly to the email this PDF arrived in, or reach us at sales@bettersight.io.", **_BLOCK)
return bytes(pdf.output())