feat(pdf): @faunosteo/pdf engine — explicit inputs, envelope v1 attachment, layered reader, xmldom composition, allowlist SVG sanitiser, WinAnsi guard, rasterizer adapter; goldens reproduced

This commit is contained in:
bchanot committed 2026-10-11 13:09:17 +02:00
1 parent e7419cb4cb
commit c17956031d
46 files changed
+4396 -1

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
import { PageSizes, type PDFDocument } from 'pdf-lib'
import type { Report } from '@faunosteo/domain'
import {
COLOR_ACCENT,
COLOR_INK,
COLOR_MUTED,
EYEBROW_Y_OFFSET,
MARGIN_X,
SECTION_LABEL_GAP,
TITLE_RULE_OFFSET,
TITLE_RULE_WIDTH,
TITLE_Y_OFFSET,
} from './constants'
import type { RenderContext } from './context'
import { formatDate } from './dates'
import { drawHeader, type HeaderAssets } from './header'
import { drawText, wrapLines } from './text'
const SECTION_TOP_GAP = 28
const SECTION_BLOCK_GAP = 18
const TEXT_LINE_HEIGHT = 14
interface ConclusionSection {
label: string
body: string
color?: typeof COLOR_INK
}
function nextAppointmentText(report: Report, ctx: RenderContext): string {
const next = report.nextAppointment!
return next.kind === 'date' ? formatDate(next.date, ctx.locale) : next.text
}
function conclusionSections(
report: Report,
ctx: RenderContext,
): ConclusionSection[] {
const { labels } = ctx
const sections: ConclusionSection[] = [
{
label: labels['pdf.section.conclusion'],
body: report.conclusion || labels['pdf.empty'],
},
{
label: labels['pdf.section.recommendations'],
body: report.recommendations || labels['pdf.empty'],
},
]
if (report.nextAppointment) {
sections.push({
label: labels['pdf.section.next_appointment'],
body: nextAppointmentText(report, ctx) || labels['pdf.empty'],
color: COLOR_MUTED,
})
}
return sections
}
export async function addConclusionPage(
pdfDoc: PDFDocument,
report: Report,
ctx: RenderContext,
headerAssets: HeaderAssets,
): Promise<void> {
const { fonts, labels } = ctx
const page = pdfDoc.addPage(PageSizes.A4)
const { width, height } = page.getSize()
const max = width - MARGIN_X * 2
drawHeader(page, report, ctx, headerAssets)
const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET
drawText(page, labels['pdf.eyebrow.synthesis'], {
x: MARGIN_X,
y: eyebrowY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
drawText(page, labels['pdf.title.conclusion'], {
x: MARGIN_X,
y: titleY,
size: 22,
font: fonts.headingRegular,
color: COLOR_INK,
})
page.drawLine({
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
thickness: 2,
color: COLOR_ACCENT,
})
let cursorY = titleY - SECTION_TOP_GAP
for (const { label, body, color } of conclusionSections(report, ctx)) {
drawText(page, label, {
x: MARGIN_X,
y: cursorY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
cursorY -= SECTION_LABEL_GAP + 10
wrapLines(body, fonts.bodyRegular, 11, max).forEach((line) => {
drawText(page, line, {
x: MARGIN_X,
y: cursorY,
size: 11,
font: fonts.bodyRegular,
color: color ?? COLOR_INK,
})
cursorY -= TEXT_LINE_HEIGHT
})
cursorY -= SECTION_BLOCK_GAP
}
}
+18
View File
@@ -0,0 +1,18 @@
import { rgb } from 'pdf-lib'
/**
* Layout and colour constants shared across page renderers (header, footer,
* observation page, conclusion page). Only values identical across callers
* live here; a same-named constant with another value stays local.
*/
export const MARGIN_X = 36
export const EYEBROW_Y_OFFSET = 95
export const TITLE_Y_OFFSET = 122
export const TITLE_RULE_OFFSET = 12
export const TITLE_RULE_WIDTH = 48
export const SECTION_LABEL_GAP = 4
export const COLOR_INK = rgb(0.12, 0.11, 0.09)
export const COLOR_MUTED = rgb(0.42, 0.39, 0.35)
export const COLOR_ACCENT = rgb(0.72, 0.35, 0.25)
+11
View File
@@ -0,0 +1,11 @@
import type { PdfLabels } from '@faunosteo/domain'
import type { EmbeddedFonts } from './fonts'
export type PdfLocale = 'fr' | 'en'
/** What every page renderer needs besides the page: fonts, locale, labels. */
export interface RenderContext {
fonts: EmbeddedFonts
locale: PdfLocale
labels: PdfLabels
}
+26
View File
@@ -0,0 +1,26 @@
import type { PdfLocale } from './context'
const LOCALE_TAG: Record<PdfLocale, string> = {
fr: 'fr-FR',
en: 'en-US',
}
/**
* Long date in the locale for a `YYYY-MM-DD` value. Anything else is
* printed unchanged: a report is user data and never fails the export.
*/
export function formatDate(isoDate: string, locale: PdfLocale): string {
const match = isoDate.match(/^(\d{4})-(\d{2})-(\d{2})$/)
if (!match) return isoDate
const [, y, mo, d] = match
const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d)))
const rolledOver =
date.getUTCMonth() !== Number(mo) - 1 || date.getUTCDate() !== Number(d)
if (Number.isNaN(date.getTime()) || rolledOver) return isoDate
return new Intl.DateTimeFormat(LOCALE_TAG[locale], {
day: 'numeric',
month: 'long',
year: 'numeric',
timeZone: 'UTC',
}).format(date)
}
+17
View File
@@ -0,0 +1,17 @@
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
/** Helvetica body, Times heading: WinAnsi standard fonts (TTF planned). */
export interface EmbeddedFonts {
bodyRegular: PDFFont
bodyBold: PDFFont
headingRegular: PDFFont
}
export async function embedFonts(pdfDoc: PDFDocument): Promise<EmbeddedFonts> {
const [bodyRegular, bodyBold, headingRegular] = await Promise.all([
pdfDoc.embedFont(StandardFonts.Helvetica),
pdfDoc.embedFont(StandardFonts.HelveticaBold),
pdfDoc.embedFont(StandardFonts.TimesRoman),
])
return { bodyRegular, bodyBold, headingRegular }
}
+170
View File
@@ -0,0 +1,170 @@
import { rgb, type PDFPage } from 'pdf-lib'
import type { BrandingImages, CreditAsset } from '../branding'
import { COLOR_MUTED, MARGIN_X } from './constants'
import type { RenderContext } from './context'
import { addLinkAnnotation } from './linkAnnotation'
import { drawText, measure } from './text'
const FOOTER_BASE_Y = 20
const FONT_SIZE = 8
const LOGO_W = 80
const LOGO_H = 30
const ROW_Y = FOOTER_BASE_Y + 14
const TEXT_BASE_Y = ROW_Y + 6
const CREDIT_LOGO_H = 16
const POWERED_LOGO_W = 70
const COLOR_RULE = rgb(0.85, 0.83, 0.8)
const COLOR_CREDIT = rgb(0.28, 0.56, 0.42)
function drawRule(page: PDFPage): void {
const { width } = page.getSize()
const separatorY = ROW_Y + LOGO_H + 6
page.drawLine({
start: { x: MARGIN_X, y: separatorY },
end: { x: width - MARGIN_X, y: separatorY },
thickness: 0.5,
color: COLOR_RULE,
})
}
function drawSiteLogo(page: PDFPage, assets: BrandingImages): void {
if (!assets.footer) return
const rect = { x: MARGIN_X, y: ROW_Y, width: LOGO_W, height: LOGO_H }
page.drawImage(assets.footer, rect)
addLinkAnnotation(page, { ...rect, url: assets.siteUrl })
}
function drawMutedLabel(
page: PDFPage,
text: string,
x: number,
ctx: RenderContext,
): void {
drawText(page, text, {
x,
y: TEXT_BASE_Y,
size: FONT_SIZE,
font: ctx.fonts.bodyRegular,
color: COLOR_MUTED,
})
}
/** The credit's fallback text in the accent colour, linked. */
function drawCreditText(
page: PDFPage,
credit: CreditAsset,
x: number,
ctx: RenderContext,
): void {
const font = ctx.fonts.bodyRegular
drawText(page, credit.fallbackText, {
x,
y: TEXT_BASE_Y,
size: FONT_SIZE,
font,
color: COLOR_CREDIT,
})
addLinkAnnotation(page, {
x,
y: TEXT_BASE_Y - 2,
width: measure(font, credit.fallbackText, FONT_SIZE),
height: FONT_SIZE + 4,
url: credit.url,
})
}
function drawCreditLogo(
page: PDFPage,
credit: CreditAsset & { image: NonNullable<CreditAsset['image']> },
x: number,
width: number,
): void {
const rect = { x, y: ROW_Y + 2, width, height: CREDIT_LOGO_H }
page.drawImage(credit.image, rect)
addLinkAnnotation(page, { ...rect, url: credit.url })
}
/** Centred block: label then the fixed-width logo or the fallback text. */
function drawPoweredBy(
page: PDFPage,
credit: CreditAsset,
ctx: RenderContext,
): void {
const { width } = page.getSize()
const font = ctx.fonts.bodyRegular
const label = `${ctx.labels['footer.powered_by']} `
const labelW = measure(font, label, FONT_SIZE)
const creditW = credit.image
? POWERED_LOGO_W
: measure(font, credit.fallbackText, FONT_SIZE)
const x = (width - labelW - creditW) / 2
drawMutedLabel(page, label, x, ctx)
if (credit.image) {
drawCreditLogo(
page,
{ ...credit, image: credit.image },
x + labelW,
POWERED_LOGO_W,
)
} else {
drawCreditText(page, credit, x + labelW, ctx)
}
}
/** Right-aligned block: label then the aspect-sized logo or the handle. */
function drawPartner(
page: PDFPage,
credit: CreditAsset,
ctx: RenderContext,
): void {
const { width } = page.getSize()
const font = ctx.fonts.bodyRegular
const label = `${ctx.labels['footer.in_partnership']} `
const labelW = measure(font, label, FONT_SIZE)
const creditW = credit.image
? CREDIT_LOGO_H * (credit.image.width / credit.image.height)
: measure(font, credit.fallbackText, FONT_SIZE)
const x = width - MARGIN_X - labelW - creditW
drawMutedLabel(page, label, x, ctx)
if (credit.image) {
drawCreditLogo(
page,
{ ...credit, image: credit.image },
x + labelW,
creditW,
)
} else {
drawCreditText(page, credit, x + labelW, ctx)
}
}
function drawPageNumber(
page: PDFPage,
pageNumber: number,
totalPages: number,
ctx: RenderContext,
): void {
const { width } = page.getSize()
const text = `${pageNumber} / ${totalPages}`
drawText(page, text, {
x: (width - measure(ctx.fonts.bodyRegular, text, FONT_SIZE)) / 2,
y: FOOTER_BASE_Y + 2,
size: FONT_SIZE,
font: ctx.fonts.bodyRegular,
color: COLOR_MUTED,
})
}
/** Rule, site logo, powered-by credit, partner credit, page number. */
export function drawFooter(
page: PDFPage,
pagination: { pageNumber: number; totalPages: number },
ctx: RenderContext,
assets: BrandingImages,
): void {
drawRule(page)
drawSiteLogo(page, assets)
if (assets.poweredBy) drawPoweredBy(page, assets.poweredBy, ctx)
if (assets.partner) drawPartner(page, assets.partner, ctx)
drawPageNumber(page, pagination.pageNumber, pagination.totalPages, ctx)
}
+112
View File
@@ -0,0 +1,112 @@
import type { PDFImage, PDFPage } from 'pdf-lib'
import type { Report } from '@faunosteo/domain'
import { COLOR_INK, COLOR_MUTED, MARGIN_X } from './constants'
import type { RenderContext } from './context'
import { formatDate } from './dates'
import { addLinkAnnotation } from './linkAnnotation'
import { drawText, measure } from './text'
const TOP_Y = 800
const LOGO_WIDTH = 100
const LOGO_HEIGHT = 38
export interface HeaderAssets {
logo: PDFImage | null
siteUrl: string
}
function practitionerLines(report: Report, ctx: RenderContext): string[] {
const { practitioner } = report
return [
practitioner.name,
practitioner.cabinet,
practitioner.contact,
practitioner.siret
? `${ctx.labels['pdf.siret_prefix']}${practitioner.siret}`
: undefined,
].filter((line): line is string => Boolean(line))
}
function animalLines(report: Report, ctx: RenderContext): string[] {
const animalLine = [
report.animal.name,
report.animal.breed ? `(${report.animal.breed})` : '',
report.animal.age ? `· ${report.animal.age}` : '',
]
.filter(Boolean)
.join(' ')
return [
animalLine,
`${ctx.labels['pdf.owner_prefix']}${report.owner.name}`,
formatDate(report.date, ctx.locale),
]
}
function drawLeftColumn(
page: PDFPage,
lines: string[],
ctx: RenderContext,
): void {
lines.forEach((line, i) => {
drawText(page, line, {
x: MARGIN_X,
y: TOP_Y - i * 12,
size: i === 0 ? 11 : 9,
font: i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular,
color: i === 0 ? COLOR_INK : COLOR_MUTED,
})
})
}
function drawRightColumn(
page: PDFPage,
lines: string[],
ctx: RenderContext,
): void {
const { width } = page.getSize()
lines.forEach((line, i) => {
const size = i === 0 ? 11 : 9
const font = i === 0 ? ctx.fonts.bodyBold : ctx.fonts.bodyRegular
drawText(page, line, {
x: width - MARGIN_X - measure(font, line, size),
y: TOP_Y - i * 12,
size,
font,
color: i === 0 ? COLOR_INK : COLOR_MUTED,
})
})
}
function drawLogo(page: PDFPage, assets: HeaderAssets): void {
if (!assets.logo) return
const { width } = page.getSize()
const rect = {
x: (width - LOGO_WIDTH) / 2,
y: TOP_Y - LOGO_HEIGHT + 10,
width: LOGO_WIDTH,
height: LOGO_HEIGHT,
}
page.drawImage(assets.logo, rect)
addLinkAnnotation(page, { ...rect, url: assets.siteUrl })
}
/** Practitioner block left, logo centred, animal block right, then a rule. */
export function drawHeader(
page: PDFPage,
report: Report,
ctx: RenderContext,
assets: HeaderAssets,
): void {
const { width } = page.getSize()
const left = practitionerLines(report, ctx)
drawLeftColumn(page, left, ctx)
drawLogo(page, assets)
drawRightColumn(page, animalLines(report, ctx), ctx)
const separatorY = TOP_Y - Math.max(left.length * 12, LOGO_HEIGHT) - 8
page.drawLine({
start: { x: MARGIN_X, y: separatorY },
end: { x: width - MARGIN_X, y: separatorY },
thickness: 0.5,
color: COLOR_MUTED,
})
}
+36
View File
@@ -0,0 +1,36 @@
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
export interface LinkRect {
x: number
y: number
width: number
height: number
url: string
}
/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
const context = page.doc.context
const actionDict = context.obj({
Type: 'Action',
S: 'URI',
URI: PDFString.of(rect.url),
})
const annotDict = context.obj({
Type: 'Annot',
Subtype: 'Link',
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
Border: [0, 0, 0],
A: actionDict,
})
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
if (annots) {
annots.push(context.register(annotDict))
} else {
const arr = context.obj([context.register(annotDict)])
page.node.set(PDFName.of('Annots'), arr)
}
}
+634
View File
@@ -0,0 +1,634 @@
import {
PageSizes,
rgb,
type PDFDocument,
type PDFImage,
type PDFPage,
} from 'pdf-lib'
import {
pickLabel,
type Finding,
type Observation,
type PdfLabels,
type Report,
type ReportZone,
type Severity,
type SheetIndex,
type SheetSnapshot,
} from '@faunosteo/domain'
import { renderHighlightedView } from '../svg/view'
import type { ExportWarning, Rasterizer } from '../types'
import {
COLOR_ACCENT,
COLOR_INK,
EYEBROW_Y_OFFSET,
MARGIN_X,
SECTION_LABEL_GAP,
TITLE_RULE_OFFSET,
TITLE_RULE_WIDTH,
TITLE_Y_OFFSET,
} from './constants'
import type { PdfLocale, RenderContext } from './context'
import type { EmbeddedFonts } from './fonts'
import { drawHeader, type HeaderAssets } from './header'
import { drawText, measure, wrapLines } from './text'
const MARGIN_BOTTOM = 48
const IMAGE_TOP_GAP = 32
const IMAGE_LABEL_GAP = 14
const IMAGE_BOTTOM_GAP = 14
const IMAGE_COL_GAP = 16
const IMAGE_ROW_GAP = 12
const IMAGE_MIN_CELL_H = 60
const TEXT_TOP_GAP = 10
const TEXT_LINE_HEIGHT = 13
const SECTION_BLOCK_GAP = 10
const COLOR_WHITE = rgb(1, 1, 1)
const SEVERITY_BG: Record<Severity, ReturnType<typeof rgb>> = {
mild: rgb(0.55, 0.65, 0.45),
moderate: rgb(0.85, 0.55, 0.18),
severe: rgb(0.78, 0.2, 0.2),
}
const SECTION_TEXT_SIZE = 10
const SEPARATOR_GLYPH = '•'
const SEPARATOR_SIZE = 14
const SEPARATOR_SIDE_GAP = 5
/** Items of a section joined by this print as a segmented line. */
const ITEM_JOIN = ' · '
/** Width of the visible separator block including the empty space on each side. */
function separatorWidth(fonts: EmbeddedFonts): number {
return (
measure(fonts.bodyBold, SEPARATOR_GLYPH, SEPARATOR_SIZE) +
SEPARATOR_SIDE_GAP * 2
)
}
/** Counts the line breaks a list of items would consume when laid out on a maxWidth line. */
function countSegmentedLines(
items: string[],
fonts: EmbeddedFonts,
maxWidth: number,
): number {
if (items.length === 0) return 1
const sepW = separatorWidth(fonts)
let lines = 1
let x = 0
for (let i = 0; i < items.length; i += 1) {
const itemW = measure(fonts.bodyRegular, items[i]!, SECTION_TEXT_SIZE)
if (x + itemW > maxWidth && x > 0) {
lines += 1
x = 0
}
x += itemW
if (i < items.length - 1) {
if (x + sepW > maxWidth) {
lines += 1
x = 0
} else {
x += sepW
}
}
}
return lines
}
interface SegmentCursor {
x: number
y: number
}
function drawSeparator(
page: PDFPage,
cursor: SegmentCursor,
fonts: EmbeddedFonts,
): void {
const baselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
drawText(page, SEPARATOR_GLYPH, {
x: cursor.x + SEPARATOR_SIDE_GAP,
y: cursor.y - baselineOffset,
size: SEPARATOR_SIZE,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
}
/**
* Renders a list of items separated by a visibly larger accent-coloured
* bullet. Returns the cursor y *below* the last line drawn.
*/
function drawSegmentedText(
page: PDFPage,
items: string[],
start: SegmentCursor,
maxWidth: number,
fonts: EmbeddedFonts,
): number {
if (items.length === 0) return start.y - TEXT_LINE_HEIGHT
const sepW = separatorWidth(fonts)
const cursor = { ...start }
for (let i = 0; i < items.length; i += 1) {
const item = items[i]!
const itemW = measure(fonts.bodyRegular, item, SECTION_TEXT_SIZE)
if (cursor.x + itemW > start.x + maxWidth && cursor.x > start.x) {
cursor.x = start.x
cursor.y -= TEXT_LINE_HEIGHT
}
drawText(page, item, {
x: cursor.x,
y: cursor.y,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
cursor.x += itemW
if (i === items.length - 1) continue
if (cursor.x + sepW > start.x + maxWidth) {
cursor.x = start.x
cursor.y -= TEXT_LINE_HEIGHT
} else {
drawSeparator(page, cursor, fonts)
cursor.x += sepW
}
}
return cursor.y - TEXT_LINE_HEIGHT
}
/** Parameters needed to render one observation page. */
export interface ObservationPageContext {
pdfDoc: PDFDocument
report: Report
observation: Observation
obsIndex: number
sheet: SheetIndex
snapshot: SheetSnapshot
ctx: RenderContext
headerAssets: HeaderAssets
rasterizer: Rasterizer
warnings: ExportWarning[]
}
interface PageDrawContext {
page: PDFPage
fonts: EmbeddedFonts
width: number
}
interface RenderedImage {
label: string
img: PDFImage
aspect: number
}
interface ObservationSection {
label: string
value: string
}
function drawSeverityPill(
draw: PageDrawContext,
severity: Severity,
labels: PdfLabels,
anchor: { numW: number; titleY: number },
): void {
const { page, fonts } = draw
const sevText = labels[`severity.${severity}`].toUpperCase()
const sevSize = 9
const padX = 8
const padY = 4
const pillW = measure(fonts.bodyBold, sevText, sevSize) + padX * 2
const pillH = sevSize + padY * 2
const pillX = MARGIN_X + anchor.numW + 14
const pillY = anchor.titleY + 4
page.drawRectangle({
x: pillX,
y: pillY,
width: pillW,
height: pillH,
color: SEVERITY_BG[severity],
})
drawText(page, sevText, {
x: pillX + padX,
y: pillY + padY,
size: sevSize,
font: fonts.bodyBold,
color: COLOR_WHITE,
})
}
function drawObservationTitleBlock(
draw: PageDrawContext,
labels: PdfLabels,
obsIndex: number,
severity: Severity | undefined,
): number {
const { page, fonts } = draw
const { height } = page.getSize()
const eyebrowY = height - EYEBROW_Y_OFFSET
const titleY = height - TITLE_Y_OFFSET
const obsLabel = String(obsIndex + 1).padStart(2, '0')
drawText(page, labels['pdf.eyebrow.observation'], {
x: MARGIN_X,
y: eyebrowY,
size: 9,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
drawText(page, obsLabel, {
x: MARGIN_X,
y: titleY,
size: 22,
font: fonts.headingRegular,
color: COLOR_INK,
})
if (severity) {
const numW = measure(fonts.headingRegular, obsLabel, 22)
drawSeverityPill(draw, severity, labels, { numW, titleY })
}
page.drawLine({
start: { x: MARGIN_X, y: titleY - TITLE_RULE_OFFSET },
end: { x: MARGIN_X + TITLE_RULE_WIDTH, y: titleY - TITLE_RULE_OFFSET },
thickness: 2,
color: COLOR_ACCENT,
})
return titleY
}
/** Unique views the observation touches and the snapshot holds, main first. */
export function observationViewIds(
sheet: SheetIndex,
observation: Observation,
): string[] {
return [...new Set(observation.zones.map((z) => z.viewId))]
.filter((id) => sheet.view(id))
.sort(
(a, b) =>
Number(b === sheet.mainView.id) - Number(a === sheet.mainView.id),
)
}
function viewLabel(
sheet: SheetIndex,
viewId: string,
ctx: RenderContext,
): string {
const view = sheet.view(viewId)!
if (view.kind === 'main') return ctx.labels['pdf.view.general']
const name = pickLabel(view.name, ctx.locale).toUpperCase()
return `${ctx.labels['pdf.view.detail_prefix']}${name}`
}
interface RasterisedView {
viewId: string
png: Uint8Array | null
}
/** One view rasterised; a failure yields null and a warning, never a throw. */
async function rasteriseView(
page: ObservationPageContext,
viewId: string,
): Promise<RasterisedView> {
try {
const { svg, size } = renderHighlightedView(
page.snapshot,
viewId,
page.observation,
)
return { viewId, png: await page.rasterizer(svg, size) }
} catch {
page.warnings.push({
kind: 'view_raster_failed',
observationId: page.observation.id,
viewId,
})
return { viewId, png: null }
}
}
/** Rasterisation in parallel, embedding in view order so bytes stay stable. */
async function buildObservationImages(
page: ObservationPageContext,
): Promise<RenderedImage[]> {
const viewIds = observationViewIds(page.sheet, page.observation)
const rasters = await Promise.all(
viewIds.map((viewId) => rasteriseView(page, viewId)),
)
const rendered: RenderedImage[] = []
for (const { viewId, png } of rasters) {
if (!png) continue
try {
const img = await page.pdfDoc.embedPng(png)
rendered.push({
label: viewLabel(page.sheet, viewId, page.ctx),
img,
aspect: img.width > 0 ? img.height / img.width : 0.6,
})
} catch {
page.warnings.push({
kind: 'view_raster_failed',
observationId: page.observation.id,
viewId,
})
}
}
return rendered
}
/** Zone name: snapshot annotation, else the report's label snapshot, else the id. */
function zoneText(z: ReportZone, sheet: SheetIndex, locale: PdfLocale): string {
const annotation = sheet.annotation(z.annotationId)
if (annotation) return pickLabel(sheet.name(annotation), locale)
const snapshot =
locale === 'en'
? z.labelEnSnapshot || z.labelFrSnapshot
: z.labelFrSnapshot || z.labelEnSnapshot
return snapshot || z.annotationId
}
function sideLabel(side: 'left' | 'right', labels: PdfLabels): string {
return labels[side === 'left' ? 'lateral.left' : 'lateral.right']
}
function describeObservationZones(
zones: ReportZone[],
sheet: SheetIndex,
ctx: RenderContext,
): string {
return zones
.map((z) => {
const v = z.vertebrae?.length
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
: ''
const side = z.side ? ` (${sideLabel(z.side, ctx.labels)})` : ''
return `${zoneText(z, sheet, ctx.locale)}${v}${side}`
})
.join(ITEM_JOIN)
}
/** Finding group heading: snapshot finding-zone name, else the id as is. */
function findingZoneName(
zoneId: string,
sheet: SheetIndex,
locale: PdfLocale,
): string {
const zone = sheet.findingZone(zoneId)
return zone ? pickLabel(zone.name, locale) : zoneId
}
function findingText(f: Finding, locale: PdfLocale): string {
const label = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
return f.requiresVetReferral ? `(!) ${label}` : label
}
/** Groups findings by zone+side, one section per group; snapshots give the text. */
function buildFindingsSections(
findings: Finding[],
sheet: SheetIndex,
ctx: RenderContext,
): ObservationSection[] {
const byZoneSide = new Map<string, Finding[]>()
for (const f of findings) {
const key = f.side ? `${f.findingZoneId}:${f.side}` : f.findingZoneId
byZoneSide.set(key, [...(byZoneSide.get(key) ?? []), f])
}
const sections: ObservationSection[] = []
for (const [key, group] of byZoneSide) {
const zoneId = key.split(':')[0]!
const side = group[0]?.side
let zoneName = findingZoneName(zoneId, sheet, ctx.locale)
if (side) zoneName = `${zoneName} (${sideLabel(side, ctx.labels)})`
sections.push({
label: `${ctx.labels['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
value: group.map((f) => findingText(f, ctx.locale)).join(ITEM_JOIN),
})
}
return sections
}
function buildObservationSections(
observation: Observation,
sheet: SheetIndex,
ctx: RenderContext,
): ObservationSection[] {
const { labels } = ctx
const zonesText = describeObservationZones(observation.zones, sheet, ctx)
const sections: ObservationSection[] = [
{
label: labels['pdf.section.zones'],
value: zonesText || labels['pdf.empty'],
},
...buildFindingsSections(observation.findings, sheet, ctx),
]
if (observation.freeTextFindings.length) {
sections.push({
label: labels['pdf.section.free_findings'],
value: observation.freeTextFindings.join(ITEM_JOIN),
})
}
if (observation.severity) {
sections.push({
label: labels['pdf.section.severity'],
value: labels[`severity.${observation.severity}`],
})
}
if (observation.comment.trim()) {
sections.push({
label: labels['pdf.section.comment'],
value: observation.comment.trim(),
})
}
return sections
}
function estimateSectionsHeight(
sections: ObservationSection[],
fonts: EmbeddedFonts,
maxTextW: number,
): number {
let h = TEXT_TOP_GAP
for (const { value } of sections) {
const lineCount = value.includes(ITEM_JOIN)
? countSegmentedLines(value.split(ITEM_JOIN), fonts, maxTextW)
: wrapLines(value, fonts.bodyRegular, SECTION_TEXT_SIZE, maxTextW).length
h +=
SECTION_LABEL_GAP + 9 + lineCount * TEXT_LINE_HEIGHT + SECTION_BLOCK_GAP
}
return h
}
interface ImageGrid {
cols: number
rows: number
cellW: number
offsetX: number
rowBudget: number
}
function imageGridOf(
rendered: RenderedImage[],
width: number,
availH: number,
): ImageGrid {
const isSingle = rendered.length === 1
const cols = isSingle ? 1 : 2
const rows = Math.ceil(rendered.length / cols)
const fullCellW = (width - MARGIN_X * 2 - IMAGE_COL_GAP * (cols - 1)) / cols
const cellW = isSingle ? fullCellW / 2 : fullCellW
return {
cols,
rows,
cellW,
offsetX: isSingle ? (fullCellW - cellW) / 2 : 0,
rowBudget: Math.max(
IMAGE_MIN_CELL_H,
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
),
}
}
/** One row of the grid: labels above, then the images; returns the row height. */
function drawImageRow(
draw: PageDrawContext,
rowItems: RenderedImage[],
grid: ImageGrid,
topY: number,
): number {
const { page, fonts } = draw
const cellHs = rowItems.map((it) =>
Math.min(grid.cellW * it.aspect, grid.rowBudget),
)
const cellX = (c: number) =>
MARGIN_X + grid.offsetX + c * (grid.cellW + IMAGE_COL_GAP)
rowItems.forEach((it, c) => {
drawText(page, it.label, {
x: cellX(c),
y: topY,
size: 8,
font: fonts.bodyBold,
color: COLOR_ACCENT,
})
})
const imagesY = topY - IMAGE_LABEL_GAP
rowItems.forEach((it, c) => {
page.drawImage(it.img, {
x: cellX(c),
y: imagesY - cellHs[c]!,
width: grid.cellW,
height: cellHs[c]!,
})
})
return Math.max(0, ...cellHs)
}
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
function drawObservationImageGrid(
draw: PageDrawContext,
rendered: RenderedImage[],
startY: number,
reservedBottom: number,
): number {
if (rendered.length === 0) return startY
const availH = Math.max(IMAGE_MIN_CELL_H, startY - reservedBottom)
const grid = imageGridOf(rendered, draw.width, availH)
let cursorY = startY
for (let r = 0; r < grid.rows; r += 1) {
const rowItems = rendered.slice(r * grid.cols, r * grid.cols + grid.cols)
const rowH = drawImageRow(draw, rowItems, grid, cursorY)
cursorY -= IMAGE_LABEL_GAP + rowH
if (r < grid.rows - 1) cursorY -= IMAGE_ROW_GAP
}
return cursorY - IMAGE_BOTTOM_GAP
}
function drawSectionValue(
draw: PageDrawContext,
value: string,
startY: number,
maxTextW: number,
): number {
const { page, fonts } = draw
if (value.includes(ITEM_JOIN)) {
return drawSegmentedText(
page,
value.split(ITEM_JOIN),
{ x: MARGIN_X, y: startY },
maxTextW,
fonts,
)
}
let cursorY = startY
for (const line of wrapLines(
value,
fonts.bodyRegular,
SECTION_TEXT_SIZE,
maxTextW,
)) {
drawText(page, line, {
x: MARGIN_X,
y: cursorY,
size: SECTION_TEXT_SIZE,
font: fonts.bodyRegular,
color: COLOR_INK,
})
cursorY -= TEXT_LINE_HEIGHT
}
return cursorY
}
function drawObservationSections(
draw: PageDrawContext,
sections: ObservationSection[],
startY: number,
maxTextW: number,
): number {
let cursorY = startY
for (const { label, value } of sections) {
drawText(draw.page, label, {
x: MARGIN_X,
y: cursorY,
size: 8,
font: draw.fonts.bodyBold,
color: COLOR_ACCENT,
})
cursorY -= SECTION_LABEL_GAP + 9
cursorY = drawSectionValue(draw, value, cursorY, maxTextW)
cursorY -= SECTION_BLOCK_GAP
}
return cursorY
}
export async function addObservationPage(
input: ObservationPageContext,
): Promise<void> {
const { pdfDoc, report, observation, obsIndex, sheet, ctx, headerAssets } =
input
const page = pdfDoc.addPage(PageSizes.A4)
const { width } = page.getSize()
drawHeader(page, report, ctx, headerAssets)
const draw: PageDrawContext = { page, fonts: ctx.fonts, width }
const titleY = drawObservationTitleBlock(
draw,
ctx.labels,
obsIndex,
observation.severity,
)
const rendered = await buildObservationImages(input)
const maxTextW = width - MARGIN_X * 2
const sections = buildObservationSections(observation, sheet, ctx)
const reservedBottom =
MARGIN_BOTTOM +
estimateSectionsHeight(sections, ctx.fonts, maxTextW) +
IMAGE_BOTTOM_GAP
let cursorY = drawObservationImageGrid(
draw,
rendered,
titleY - IMAGE_TOP_GAP,
reservedBottom,
)
cursorY -= TEXT_TOP_GAP
drawObservationSections(draw, sections, cursorY, maxTextW)
}
+46
View File
@@ -0,0 +1,46 @@
import type { PDFFont, PDFPage, PDFPageDrawTextOptions } from 'pdf-lib'
import { safeText } from '../text'
/**
* Every string reaches pdf-lib through these three helpers, so a glyph the
* standard fonts cannot encode never throws at draw or measure time.
*/
export function measure(font: PDFFont, text: string, size: number): number {
return font.widthOfTextAtSize(safeText(text), size)
}
export function drawText(
page: PDFPage,
text: string,
options: PDFPageDrawTextOptions,
): void {
page.drawText(safeText(text), options)
}
/**
* Greedy word-wrap: splits `text` into lines whose rendered width at
* `size` points stays within `max` for the given font. Whitespace of any
* kind separates words first, then each word is made safe.
*/
export function wrapLines(
text: string,
font: PDFFont,
size: number,
max: number,
): string[] {
const words = text.split(/\s+/).map(safeText)
const lines: string[] = []
let line = ''
for (const w of words) {
const test = line ? `${line} ${w}` : w
if (measure(font, test, size) > max && line) {
lines.push(line)
line = w
} else {
line = test
}
}
if (line) lines.push(line)
return lines
}