feat(app): export and import through @faunosteo/pdf — snapshot, archived branding and labels, browser rasterizer, imported archive kept in session, explicit rebase with messages; legacy PDF modules removed
This commit is contained in:
1 parent
20dafc0b00
commit
9bd5173a9c
43 files changed
+1492
-1989
No files matched your search
@@ -1,200 +0,0 @@
|
||||
import { AFRelationship, type PDFDocument } from 'pdf-lib'
|
||||
import {
|
||||
readReportDocument,
|
||||
REPORT_VERSION,
|
||||
UnsupportedReportVersionError,
|
||||
type MigrationOutcome,
|
||||
type Report,
|
||||
type ReportMigrationMap,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* The report document travels inside the PDF as a native attachment.
|
||||
* Written as v3; read back as v3, or as v2 migrated through the sheet's
|
||||
* migration map (the practitioner's archive). Any other version is refused
|
||||
* with the found version.
|
||||
*/
|
||||
|
||||
const FILENAME = 'osteo-report.json'
|
||||
|
||||
export class IncompatibleReportVersionError extends Error {
|
||||
constructor(public readonly foundVersion: number | null) {
|
||||
super(`incompatible_version:${foundVersion ?? 'unknown'}`)
|
||||
this.name = 'IncompatibleReportVersionError'
|
||||
}
|
||||
}
|
||||
|
||||
export async function attachReportJson(
|
||||
pdfDoc: PDFDocument,
|
||||
report: Report,
|
||||
): Promise<void> {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(report, null, 2))
|
||||
await pdfDoc.attach(bytes, FILENAME, {
|
||||
mimeType: 'application/json',
|
||||
description: `Faunosteo state v${REPORT_VERSION}`,
|
||||
creationDate: new Date(),
|
||||
modificationDate: new Date(),
|
||||
afRelationship: AFRelationship.Data,
|
||||
})
|
||||
}
|
||||
|
||||
export interface ExtractedReport extends MigrationOutcome {
|
||||
/** True when the attachment was an older version lifted to v3. */
|
||||
migrated: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw report document carried by the PDF, of whatever version, before
|
||||
* any migration: what the archive check tool shows next to the v3 result.
|
||||
* Throws when the PDF carries no Faunosteo attachment or an oversized one.
|
||||
*/
|
||||
export async function readAttachedDocument(
|
||||
pdfDoc: PDFDocument,
|
||||
): Promise<unknown> {
|
||||
const bytes = await attachmentBytes(pdfDoc)
|
||||
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
|
||||
throw new Error('attachment too large')
|
||||
}
|
||||
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
|
||||
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
|
||||
if (versionOf(data) === null) {
|
||||
throw new Error('attachment carries no report version')
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
export async function extractReportJson(
|
||||
pdfDoc: PDFDocument,
|
||||
map: ReportMigrationMap,
|
||||
): Promise<ExtractedReport> {
|
||||
const data = await readAttachedDocument(pdfDoc)
|
||||
try {
|
||||
return {
|
||||
...readReportDocument(data, map),
|
||||
migrated: versionOf(data) !== REPORT_VERSION,
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof UnsupportedReportVersionError) {
|
||||
throw new IncompatibleReportVersionError(err.foundVersion)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {
|
||||
const maybeApi = pdfDoc as unknown as {
|
||||
getAttachments?: () => Array<{ name: string; data: Uint8Array }>
|
||||
}
|
||||
if (typeof maybeApi.getAttachments === 'function') {
|
||||
const list = maybeApi.getAttachments()
|
||||
if (list && list.length) {
|
||||
const hit =
|
||||
list.find(
|
||||
(a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'),
|
||||
) ?? list[0]
|
||||
return hit.data
|
||||
}
|
||||
}
|
||||
const fallback = await traverseForJsonAttachment(pdfDoc)
|
||||
if (!fallback) throw new Error('No osteo-report attachment found')
|
||||
return fallback
|
||||
}
|
||||
|
||||
/** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */
|
||||
const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
|
||||
|
||||
function versionOf(data: unknown): number | null {
|
||||
if (data === null || typeof data !== 'object') return null
|
||||
const v = (data as { version?: unknown }).version
|
||||
return typeof v === 'number' ? v : null
|
||||
}
|
||||
|
||||
interface RawObj {
|
||||
contents?: Uint8Array
|
||||
dict?: { entries?: () => Array<[unknown, unknown]> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard ceiling on inflated attachment size. A valid report JSON is far
|
||||
* smaller; anything bigger is a decompression bomb or corruption.
|
||||
*/
|
||||
const MAX_INFLATED_BYTES = MAX_ATTACHMENT_BYTES
|
||||
|
||||
/** Exported for tests. Returns null on failure or when the cap is exceeded. */
|
||||
export async function inflateFlate(
|
||||
bytes: Uint8Array,
|
||||
): Promise<Uint8Array | null> {
|
||||
if (typeof DecompressionStream === 'undefined') return null
|
||||
try {
|
||||
const stream = new Blob([bytes as BlobPart])
|
||||
.stream()
|
||||
.pipeThrough(new DecompressionStream('deflate'))
|
||||
const reader = stream.getReader()
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
if (total > MAX_INFLATED_BYTES) {
|
||||
await reader.cancel()
|
||||
return null
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
const out = new Uint8Array(total)
|
||||
let offset = 0
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset)
|
||||
offset += c.byteLength
|
||||
}
|
||||
return out
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function dictHasFlateFilter(entries: Array<[unknown, unknown]>): boolean {
|
||||
for (const [k, v] of entries) {
|
||||
if (String(k).includes('Filter') && String(v).includes('FlateDecode'))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function traverseForJsonAttachment(
|
||||
pdfDoc: PDFDocument,
|
||||
): Promise<Uint8Array | null> {
|
||||
const ctx = (
|
||||
pdfDoc as unknown as {
|
||||
context: { enumerateIndirectObjects(): Array<[unknown, RawObj]> }
|
||||
}
|
||||
).context
|
||||
for (const [, obj] of ctx.enumerateIndirectObjects()) {
|
||||
if (!obj || typeof obj !== 'object') continue
|
||||
if (!(obj.contents instanceof Uint8Array)) continue
|
||||
const entries = obj.dict?.entries?.() ?? []
|
||||
let isEmbeddedFile = false
|
||||
let isJsonSubtype = false
|
||||
for (const [k, v] of entries) {
|
||||
const ks = String(k)
|
||||
const vs = String(v)
|
||||
if (ks.includes('Type') && vs.includes('EmbeddedFile'))
|
||||
isEmbeddedFile = true
|
||||
// PDF name syntax escapes '/' as '#2F': /application#2Fjson
|
||||
if (
|
||||
ks.includes('Subtype') &&
|
||||
(vs.includes('application/json') || vs.includes('application#2Fjson'))
|
||||
) {
|
||||
isJsonSubtype = true
|
||||
}
|
||||
}
|
||||
if (!isEmbeddedFile && !isJsonSubtype) continue
|
||||
if (dictHasFlateFilter(entries)) {
|
||||
const inflated = await inflateFlate(obj.contents)
|
||||
if (inflated) return inflated
|
||||
}
|
||||
return obj.contents
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { Branding, ImageAsset } from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
|
||||
* the four `public/` files fetched by their current URLs, each failure
|
||||
* leaving its slot empty with a warning (the page then prints the credit's
|
||||
* fallback text), plus the credit URLs. The result travels inside the
|
||||
* archive, so a re-export never needs these files again.
|
||||
*/
|
||||
|
||||
// shortcut: the site URL and the credit constants belong to the runtime
|
||||
// config (ConfigProvider); they live here until AppConfig carries them.
|
||||
const SITE_URL = 'https://faunosteo.com'
|
||||
const POWERED_BY = {
|
||||
url: 'https://zenquality.fr',
|
||||
fallbackText: 'zenquality.fr',
|
||||
}
|
||||
const PARTNER = {
|
||||
url: 'https://www.instagram.com/paws.iin.harmony',
|
||||
fallbackText: '@paws.iin.harmony',
|
||||
}
|
||||
|
||||
const HEADER_LOGO_URL = '/assets/faunosteo_logo_horizontal-512.png'
|
||||
const FOOTER_LOGO_URL = '/assets/faunosteo-horizontal-com-512.png'
|
||||
const POWERED_BY_LOGO_URL = '/brand/zenquality-logo-fr.png'
|
||||
const PARTNER_LOGO_URL = '/Paws_in_harmony.svg'
|
||||
|
||||
/** btoa takes a binary string; chunking keeps the argument list small. */
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
const CHUNK = 0x8000
|
||||
let binary = ''
|
||||
for (let i = 0; i < bytes.length; i += CHUNK) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
|
||||
}
|
||||
return btoa(binary)
|
||||
}
|
||||
|
||||
async function fetchOk(url: string): Promise<Response> {
|
||||
const resp = await fetch(url)
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
|
||||
return resp
|
||||
}
|
||||
|
||||
async function pngAsset(url: string): Promise<ImageAsset> {
|
||||
const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer())
|
||||
return { kind: 'png', base64: bytesToBase64(bytes) }
|
||||
}
|
||||
|
||||
async function svgAsset(url: string): Promise<ImageAsset> {
|
||||
return { kind: 'svg', svg: await (await fetchOk(url)).text() }
|
||||
}
|
||||
|
||||
/** A slot fails alone: the export goes on without that logo. */
|
||||
async function slot(
|
||||
load: Promise<ImageAsset>,
|
||||
url: string,
|
||||
): Promise<ImageAsset | null> {
|
||||
try {
|
||||
return await load
|
||||
} catch (err) {
|
||||
console.warn(`Branding asset ${url} skipped:`, err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadBranding(): Promise<Branding> {
|
||||
const [headerLogo, footerLogo, poweredByLogo, partnerLogo] =
|
||||
await Promise.all([
|
||||
slot(pngAsset(HEADER_LOGO_URL), HEADER_LOGO_URL),
|
||||
slot(pngAsset(FOOTER_LOGO_URL), FOOTER_LOGO_URL),
|
||||
slot(pngAsset(POWERED_BY_LOGO_URL), POWERED_BY_LOGO_URL),
|
||||
slot(svgAsset(PARTNER_LOGO_URL), PARTNER_LOGO_URL),
|
||||
])
|
||||
return {
|
||||
siteUrl: SITE_URL,
|
||||
headerLogo,
|
||||
footerLogo,
|
||||
poweredBy: { logo: poweredByLogo, ...POWERED_BY },
|
||||
partner: { logo: partnerLogo, ...PARTNER },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { Rasterizer } from '@faunosteo/pdf'
|
||||
|
||||
/**
|
||||
* The browser side of the engine's rasterizer adapter: the engine has fixed
|
||||
* the pixel size, this module only stamps it on the SVG root and lets the
|
||||
* browser draw the SVG through an Image / canvas pair, which renders exactly
|
||||
* what the practitioner sees in the inline anatomy canvas.
|
||||
*/
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
function startsWithPngSignature(bytes: Uint8Array): boolean {
|
||||
if (bytes.length < PNG_SIGNATURE.length) return false
|
||||
return PNG_SIGNATURE.every((byte, i) => bytes[i] === byte)
|
||||
}
|
||||
|
||||
/** The root carries the namespace and the engine's size; nothing else changes. */
|
||||
function sizedSvg(svg: string, widthPx: number, heightPx: number): string {
|
||||
const root = new DOMParser().parseFromString(
|
||||
svg,
|
||||
'image/svg+xml',
|
||||
).documentElement
|
||||
if (root.namespaceURI !== SVG_NS) root.setAttribute('xmlns', SVG_NS)
|
||||
root.setAttribute('width', String(widthPx))
|
||||
root.setAttribute('height', String(heightPx))
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
function loadImage(svg: string): Promise<HTMLImageElement> {
|
||||
const blob = new Blob([svg], { type: 'image/svg+xml;charset=utf-8' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const img = new Image()
|
||||
img.decoding = 'sync'
|
||||
img.crossOrigin = 'anonymous'
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
img.onload = () => resolve(img)
|
||||
img.onerror = () =>
|
||||
reject(new Error('Browser failed to render the SVG into an Image'))
|
||||
img.src = url
|
||||
}).finally(() => URL.revokeObjectURL(url))
|
||||
}
|
||||
|
||||
function drawOnWhiteCanvas(
|
||||
img: HTMLImageElement,
|
||||
widthPx: number,
|
||||
heightPx: number,
|
||||
): HTMLCanvasElement {
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = widthPx
|
||||
canvas.height = heightPx
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Canvas 2D context unavailable')
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, widthPx, heightPx)
|
||||
ctx.drawImage(img, 0, 0, widthPx, heightPx)
|
||||
return canvas
|
||||
}
|
||||
|
||||
function canvasBlob(canvas: HTMLCanvasElement): Promise<Blob | null> {
|
||||
return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'))
|
||||
}
|
||||
|
||||
/** Fallback when toBlob yields nothing: decode the data URL by hand. */
|
||||
function pngFromDataUrl(canvas: HTMLCanvasElement): Uint8Array {
|
||||
const dataUrl = canvas.toDataURL('image/png')
|
||||
if (!dataUrl.startsWith('data:image/png')) {
|
||||
throw new Error(
|
||||
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
|
||||
)
|
||||
}
|
||||
const comma = dataUrl.indexOf(',')
|
||||
if (comma < 0) {
|
||||
throw new Error('canvas.toDataURL returned a data URL without a payload')
|
||||
}
|
||||
const binary = atob(dataUrl.slice(comma + 1))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
|
||||
if (!startsWithPngSignature(bytes)) {
|
||||
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
async function canvasToPng(canvas: HTMLCanvasElement): Promise<Uint8Array> {
|
||||
const blob = await canvasBlob(canvas)
|
||||
if (blob) {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer())
|
||||
if (startsWithPngSignature(bytes)) return bytes
|
||||
}
|
||||
return pngFromDataUrl(canvas)
|
||||
}
|
||||
|
||||
export const browserRasterizer: Rasterizer = async (
|
||||
svg,
|
||||
{ widthPx, heightPx },
|
||||
) => {
|
||||
const img = await loadImage(sizedSvg(svg, widthPx, heightPx))
|
||||
return canvasToPng(drawOnWhiteCanvas(img, widthPx, heightPx))
|
||||
}
|
||||
+21
-82
@@ -1,97 +1,36 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||
import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import type { SheetIndex } from '@/services/sheetIndex'
|
||||
import { embedFonts } from './fonts'
|
||||
import { addObservationPage } from './render/observationPage'
|
||||
import { addConclusionPage } from './render/conclusionPage'
|
||||
import { attachReportJson } from './attachment'
|
||||
import { drawFooter } from './render/footer'
|
||||
import {
|
||||
loadFaunosteoLogo,
|
||||
loadFaunosteoComLogo,
|
||||
loadZenqualityLogo,
|
||||
} from './render/logo'
|
||||
import { rasterizeSvg } from './render/svgToPng'
|
||||
import { loadBranding } from './branding'
|
||||
import { browserRasterizer } from './browserRasterizer'
|
||||
|
||||
export interface PdfExportOptions {
|
||||
locale: Locale
|
||||
}
|
||||
|
||||
/**
|
||||
* Exports a report to PDF from the in-memory document and the loaded sheet:
|
||||
* labels and drawings come from the sheet, nothing is fetched except the
|
||||
* partner logos. The v3 document is attached for re-import.
|
||||
* Exports the report as an archive PDF through the engine: the loaded sheet
|
||||
* becomes the snapshot the pages are drawn from and the attachment carries,
|
||||
* the branding is fetched once from `public/`, the browser rasterises the
|
||||
* views. Non-fatal engine warnings (a logo or a view that failed) are logged.
|
||||
*/
|
||||
export async function exportReportToPdf(
|
||||
report: Report,
|
||||
sheet: SheetIndex,
|
||||
index: SheetIndex,
|
||||
opts: PdfExportOptions,
|
||||
): Promise<Uint8Array> {
|
||||
const { locale } = opts
|
||||
const dict = getDict(locale)
|
||||
const pdfDoc = await PDFDocument.create()
|
||||
pdfDoc.setTitle(`${dict['pdf.title.suffix.bilan']}${report.animal.name}`)
|
||||
pdfDoc.setAuthor(report.practitioner.name)
|
||||
pdfDoc.setSubject(dict['pdf.subject'])
|
||||
pdfDoc.setCreationDate(new Date())
|
||||
pdfDoc.setModificationDate(new Date())
|
||||
|
||||
const fonts = await embedFonts(pdfDoc)
|
||||
|
||||
let headerLogoPdf = null
|
||||
let footerLogoPdf = null
|
||||
let zqLogoPdfImage = null
|
||||
let pawsLogoPdf = null
|
||||
try {
|
||||
headerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoLogo())
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
footerLogoPdf = await pdfDoc.embedPng(await loadFaunosteoComLogo())
|
||||
} catch (err) {
|
||||
console.warn('Faunosteo -com logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
zqLogoPdfImage = await pdfDoc.embedPng(await loadZenqualityLogo())
|
||||
} catch (err) {
|
||||
console.warn('ZenQuality logo embed failed:', err)
|
||||
}
|
||||
try {
|
||||
const resp = await fetch('/Paws_in_harmony.svg')
|
||||
if (!resp.ok) throw new Error(`Paws logo fetch failed: HTTP ${resp.status}`)
|
||||
pawsLogoPdf = await pdfDoc.embedPng(await rasterizeSvg(await resp.text()))
|
||||
} catch (err) {
|
||||
console.warn('Paws in Harmony logo embed failed:', err)
|
||||
}
|
||||
|
||||
const headerAssets = { logoPng: headerLogoPdf }
|
||||
for (let i = 0; i < report.observations.length; i += 1) {
|
||||
await addObservationPage({
|
||||
pdfDoc,
|
||||
report,
|
||||
observation: report.observations[i]!,
|
||||
obsIndex: i,
|
||||
fonts,
|
||||
sheet,
|
||||
locale,
|
||||
headerAssets,
|
||||
})
|
||||
}
|
||||
await addConclusionPage(pdfDoc, report, fonts, locale, headerAssets)
|
||||
|
||||
const pages = pdfDoc.getPages()
|
||||
const footerAssets = {
|
||||
logoPng: footerLogoPdf,
|
||||
zqLogoPng: zqLogoPdfImage,
|
||||
pawsLogoPng: pawsLogoPdf,
|
||||
}
|
||||
pages.forEach((page, idx) => {
|
||||
drawFooter(page, fonts, idx + 1, pages.length, locale, footerAssets)
|
||||
const result = await exportReportArchive({
|
||||
report,
|
||||
sheet: buildSheetSnapshot(index.sheet, report),
|
||||
branding: await loadBranding(),
|
||||
labels: defaultPdfLabels,
|
||||
locale: opts.locale,
|
||||
rasterizer: browserRasterizer,
|
||||
exportedAt: new Date(),
|
||||
})
|
||||
|
||||
await attachReportJson(pdfDoc, report)
|
||||
return pdfDoc.save()
|
||||
for (const warning of result.warnings) {
|
||||
console.warn('PDF export warning', warning)
|
||||
}
|
||||
return result.pdf
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { PDFDocument, StandardFonts, type PDFFont } from 'pdf-lib'
|
||||
|
||||
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 }
|
||||
}
|
||||
+17
-28
@@ -1,15 +1,13 @@
|
||||
import { PDFDocument } from 'pdf-lib'
|
||||
import type { ReportMigrationMap } from '@faunosteo/domain'
|
||||
import type { ArchiveReadOutcome, ReportMigrationMap } from '@faunosteo/domain'
|
||||
import {
|
||||
extractReportJson,
|
||||
IncompatibleReportVersionError,
|
||||
type ExtractedReport,
|
||||
} from './attachment'
|
||||
ArchiveReadError,
|
||||
readReportArchive,
|
||||
type ArchiveReadErrorKind,
|
||||
} from '@faunosteo/pdf'
|
||||
|
||||
export type ImportErrorKind =
|
||||
| 'invalid_pdf'
|
||||
| 'incompatible_version'
|
||||
| 'no_attachment'
|
||||
export { MAX_PDF_BYTES } from '@faunosteo/pdf'
|
||||
|
||||
export type ImportErrorKind = ArchiveReadErrorKind
|
||||
|
||||
/**
|
||||
* Localization-agnostic import error. Carries a kind discriminant + an
|
||||
@@ -26,31 +24,22 @@ export class ImportError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** A Faunosteo PDF weighs a few hundred KB; anything larger is not one. */
|
||||
export const MAX_PDF_BYTES = 50 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Reads a Faunosteo PDF back into a report document (v3, or v2 migrated
|
||||
* through the reference sheet's map). The outcome says whether a migration
|
||||
* happened and how many zones or findings it could not place.
|
||||
* Reads a Faunosteo PDF back through the engine: the report (v3 as is, v2
|
||||
* migrated through the sheet's map) and, when the file is a Step 6 archive,
|
||||
* the validated envelope or the reason its snapshot was dropped. Engine
|
||||
* failures become ImportError kinds, one to one.
|
||||
*/
|
||||
export async function importReportFromPdf(
|
||||
pdfBytes: Uint8Array,
|
||||
map: ReportMigrationMap,
|
||||
): Promise<ExtractedReport> {
|
||||
if (pdfBytes.byteLength > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
|
||||
let pdfDoc: PDFDocument
|
||||
): Promise<ArchiveReadOutcome> {
|
||||
try {
|
||||
pdfDoc = await PDFDocument.load(pdfBytes, { ignoreEncryption: true })
|
||||
} catch {
|
||||
throw new ImportError('invalid_pdf')
|
||||
}
|
||||
try {
|
||||
return await extractReportJson(pdfDoc, map)
|
||||
return await readReportArchive(pdfBytes, map)
|
||||
} catch (err) {
|
||||
if (err instanceof IncompatibleReportVersionError) {
|
||||
throw new ImportError('incompatible_version', err.foundVersion)
|
||||
if (err instanceof ArchiveReadError) {
|
||||
throw new ImportError(err.kind, err.foundVersion)
|
||||
}
|
||||
throw new ImportError('no_attachment')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { PageSizes, type PDFDocument } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { wrapLines } from './text'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
const SECTION_TOP_GAP = 28
|
||||
const SECTION_BLOCK_GAP = 18
|
||||
const TEXT_LINE_HEIGHT = 14
|
||||
|
||||
export async function addConclusionPage(
|
||||
pdfDoc: PDFDocument,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
headerAssets: HeaderAssets,
|
||||
): Promise<void> {
|
||||
const dict = getDict(locale)
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width, height } = page.getSize()
|
||||
const max = width - MARGIN_X * 2
|
||||
|
||||
drawHeader(page, report, fonts, locale, headerAssets)
|
||||
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
page.drawText(dict['pdf.eyebrow.synthesis'], {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(dict['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
|
||||
|
||||
const sections: Array<{
|
||||
label: string
|
||||
body: string
|
||||
color?: typeof COLOR_INK
|
||||
}> = [
|
||||
{
|
||||
label: dict['pdf.section.conclusion'],
|
||||
body: report.conclusion || dict['pdf.empty'],
|
||||
},
|
||||
{
|
||||
label: dict['pdf.section.recommendations'],
|
||||
body: report.recommendations || dict['pdf.empty'],
|
||||
},
|
||||
]
|
||||
if (report.nextAppointment) {
|
||||
const txt =
|
||||
report.nextAppointment.kind === 'date'
|
||||
? formatDate(report.nextAppointment.date, locale)
|
||||
: report.nextAppointment.text
|
||||
sections.push({
|
||||
label: dict['pdf.section.next_appointment'],
|
||||
body: txt || dict['pdf.empty'],
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
|
||||
for (const { label, body, color } of sections) {
|
||||
page.drawText(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) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 11,
|
||||
font: fonts.bodyRegular,
|
||||
color: color ?? COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
})
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { rgb } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Layout and color constants shared across PDF page renderers (header,
|
||||
* footer, observation page, conclusion page). Only values that are
|
||||
* byte-identical across all callers live here — a same-named constant
|
||||
* with a different value per file stays local to that file.
|
||||
*/
|
||||
|
||||
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)
|
||||
@@ -1,180 +0,0 @@
|
||||
import { rgb, type PDFPage, type PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_MUTED } from './constants'
|
||||
|
||||
const FOOTER_BASE_Y = 20
|
||||
const FONT_SIZE = 8
|
||||
|
||||
export interface FooterAssets {
|
||||
logoPng: PDFImage | null
|
||||
zqLogoPng: PDFImage | null
|
||||
pawsLogoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawFooter(
|
||||
page: PDFPage,
|
||||
fonts: EmbeddedFonts,
|
||||
pageNumber: number,
|
||||
totalPages: number,
|
||||
locale: Locale,
|
||||
assets: FooterAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
const accent = rgb(0.28, 0.56, 0.42)
|
||||
|
||||
const logoW = 80
|
||||
const logoH = 30
|
||||
const rowY = FOOTER_BASE_Y + 14
|
||||
const separatorY = rowY + logoH + 6
|
||||
|
||||
page.drawLine({
|
||||
start: { x: MARGIN_X, y: separatorY },
|
||||
end: { x: width - MARGIN_X, y: separatorY },
|
||||
thickness: 0.5,
|
||||
color: rgb(0.85, 0.83, 0.8),
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: MARGIN_X,
|
||||
y: rowY,
|
||||
width: logoW,
|
||||
height: logoH,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const poweredLabel = `${dict['footer.powered_by']} `
|
||||
const poweredLabelW = fonts.bodyRegular.widthOfTextAtSize(
|
||||
poweredLabel,
|
||||
FONT_SIZE,
|
||||
)
|
||||
const zqLogoW = 70
|
||||
const zqLogoH = 16
|
||||
const zqFallback = 'zenquality.fr'
|
||||
const zqFallbackW = fonts.bodyRegular.widthOfTextAtSize(zqFallback, FONT_SIZE)
|
||||
const poweredBlockW = assets.zqLogoPng
|
||||
? poweredLabelW + zqLogoW
|
||||
: poweredLabelW + zqFallbackW
|
||||
const poweredX = (width - poweredBlockW) / 2
|
||||
const textBaseY = rowY + 6
|
||||
|
||||
page.drawText(poweredLabel, {
|
||||
x: poweredX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const zqX = poweredX + poweredLabelW
|
||||
if (assets.zqLogoPng) {
|
||||
page.drawImage(assets.zqLogoPng, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: rowY + 2,
|
||||
width: zqLogoW,
|
||||
height: zqLogoH,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
} else {
|
||||
page.drawText(zqFallback, {
|
||||
x: zqX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: zqX,
|
||||
y: textBaseY - 2,
|
||||
width: zqFallbackW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: 'https://zenquality.fr',
|
||||
})
|
||||
}
|
||||
|
||||
const partnerLabel = `${dict['footer.in_partnership']} `
|
||||
const partnerLabelW = fonts.bodyRegular.widthOfTextAtSize(
|
||||
partnerLabel,
|
||||
FONT_SIZE,
|
||||
)
|
||||
const partnerUrl = 'https://www.instagram.com/paws.iin.harmony'
|
||||
|
||||
if (assets.pawsLogoPng) {
|
||||
const pawsLogoH = 16
|
||||
const pawsLogoW =
|
||||
pawsLogoH * (assets.pawsLogoPng.width / assets.pawsLogoPng.height)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - pawsLogoW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
const pawsX = partnerX + partnerLabelW
|
||||
page.drawImage(assets.pawsLogoPng, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: pawsX,
|
||||
y: rowY + 2,
|
||||
width: pawsLogoW,
|
||||
height: pawsLogoH,
|
||||
url: partnerUrl,
|
||||
})
|
||||
} else {
|
||||
const handle = '@paws.iin.harmony'
|
||||
const handleW = fonts.bodyRegular.widthOfTextAtSize(handle, FONT_SIZE)
|
||||
const partnerX = width - MARGIN_X - partnerLabelW - handleW
|
||||
page.drawText(partnerLabel, {
|
||||
x: partnerX,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
page.drawText(handle, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: accent,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: partnerX + partnerLabelW,
|
||||
y: textBaseY - 2,
|
||||
width: handleW,
|
||||
height: FONT_SIZE + 4,
|
||||
url: partnerUrl,
|
||||
})
|
||||
}
|
||||
|
||||
const pageText = `${pageNumber} / ${totalPages}`
|
||||
const pageW = fonts.bodyRegular.widthOfTextAtSize(pageText, FONT_SIZE)
|
||||
page.drawText(pageText, {
|
||||
x: (width - pageW) / 2,
|
||||
y: FOOTER_BASE_Y + 2,
|
||||
size: FONT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_MUTED,
|
||||
})
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import type { PDFPage, PDFImage } from 'pdf-lib'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Report } from '@faunosteo/domain'
|
||||
import type { Locale } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { formatDate } from '@/lib/dates'
|
||||
import { addLinkAnnotation } from './linkAnnotation'
|
||||
import { MARGIN_X, COLOR_INK, COLOR_MUTED } from './constants'
|
||||
|
||||
const TOP_Y = 800
|
||||
const LOGO_WIDTH = 100
|
||||
const LOGO_HEIGHT = 38
|
||||
|
||||
export interface HeaderAssets {
|
||||
logoPng: PDFImage | null
|
||||
}
|
||||
|
||||
export function drawHeader(
|
||||
page: PDFPage,
|
||||
report: Report,
|
||||
fonts: EmbeddedFonts,
|
||||
locale: Locale,
|
||||
assets: HeaderAssets,
|
||||
): void {
|
||||
const dict = getDict(locale)
|
||||
const { width } = page.getSize()
|
||||
|
||||
const y = TOP_Y
|
||||
|
||||
const left = [
|
||||
report.practitioner.name,
|
||||
report.practitioner.cabinet,
|
||||
report.practitioner.contact,
|
||||
report.practitioner.siret
|
||||
? `${dict['pdf.siret_prefix']}${report.practitioner.siret}`
|
||||
: undefined,
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
left.forEach((line, i) => {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: y - i * 12,
|
||||
size: i === 0 ? 11 : 9,
|
||||
font: i === 0 ? fonts.bodyBold : fonts.bodyRegular,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
if (assets.logoPng) {
|
||||
const logoX = (width - LOGO_WIDTH) / 2
|
||||
const logoY = y - LOGO_HEIGHT + 10
|
||||
page.drawImage(assets.logoPng, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
})
|
||||
addLinkAnnotation(page, {
|
||||
x: logoX,
|
||||
y: logoY,
|
||||
width: LOGO_WIDTH,
|
||||
height: LOGO_HEIGHT,
|
||||
url: 'https://faunosteo.com',
|
||||
})
|
||||
}
|
||||
|
||||
const animalLine = [
|
||||
report.animal.name,
|
||||
report.animal.breed ? `(${report.animal.breed})` : '',
|
||||
report.animal.age ? `· ${report.animal.age}` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
|
||||
const right = [
|
||||
animalLine,
|
||||
`${dict['pdf.owner_prefix']}${report.owner.name}`,
|
||||
formatDate(report.date, locale),
|
||||
]
|
||||
right.forEach((line, i) => {
|
||||
const size = i === 0 ? 11 : 9
|
||||
const font = i === 0 ? fonts.bodyBold : fonts.bodyRegular
|
||||
const w = font.widthOfTextAtSize(line, size)
|
||||
page.drawText(line, {
|
||||
x: width - MARGIN_X - w,
|
||||
y: y - i * 12,
|
||||
size,
|
||||
font,
|
||||
color: i === 0 ? COLOR_INK : COLOR_MUTED,
|
||||
})
|
||||
})
|
||||
|
||||
const separatorY = 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,
|
||||
})
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
|
||||
|
||||
export interface LinkRect {
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
height: number
|
||||
url: string
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
const FAUNOSTEO_LOGO = '/assets/faunosteo_logo_horizontal-512.png'
|
||||
const FAUNOSTEO_COM_LOGO = '/assets/faunosteo-horizontal-com-512.png'
|
||||
const ZENQUALITY_LOGO = '/brand/zenquality-logo-fr.png'
|
||||
|
||||
async function fetchPngBytes(path: string): Promise<Uint8Array> {
|
||||
const resp = await fetch(path)
|
||||
if (!resp.ok) throw new Error(`Logo fetch failed: HTTP ${resp.status}`)
|
||||
return new Uint8Array(await resp.arrayBuffer())
|
||||
}
|
||||
|
||||
export async function loadFaunosteoLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_LOGO)
|
||||
}
|
||||
|
||||
export async function loadFaunosteoComLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(FAUNOSTEO_COM_LOGO)
|
||||
}
|
||||
|
||||
export async function loadZenqualityLogo(): Promise<Uint8Array> {
|
||||
return fetchPngBytes(ZENQUALITY_LOGO)
|
||||
}
|
||||
@@ -1,627 +0,0 @@
|
||||
import {
|
||||
rgb,
|
||||
PageSizes,
|
||||
type PDFDocument,
|
||||
type PDFPage,
|
||||
type PDFImage,
|
||||
} from 'pdf-lib'
|
||||
import type {
|
||||
Finding,
|
||||
Observation,
|
||||
Report,
|
||||
ReportZone,
|
||||
Severity,
|
||||
} from '@faunosteo/domain'
|
||||
import type { EmbeddedFonts } from '@/pdf/fonts'
|
||||
import type { Locale, Dict } from '@/i18n/types'
|
||||
import { getDict } from '@/i18n'
|
||||
import { pickLabel, type SheetIndex } from '@/services/sheetIndex'
|
||||
import { buildViewSvg } from '@/anatomy/drawing'
|
||||
import { drawHeader, type HeaderAssets } from './header'
|
||||
import { rasterizeSvg } from './svgToPng'
|
||||
import { wrapLines } from './text'
|
||||
import {
|
||||
MARGIN_X,
|
||||
EYEBROW_Y_OFFSET,
|
||||
TITLE_Y_OFFSET,
|
||||
TITLE_RULE_OFFSET,
|
||||
TITLE_RULE_WIDTH,
|
||||
SECTION_LABEL_GAP,
|
||||
COLOR_INK,
|
||||
COLOR_MUTED,
|
||||
COLOR_ACCENT,
|
||||
} from './constants'
|
||||
|
||||
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
|
||||
|
||||
/** Width of the visible separator block including the empty space on each side. */
|
||||
function separatorWidth(fonts: EmbeddedFonts): number {
|
||||
return (
|
||||
fonts.bodyBold.widthOfTextAtSize(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 = fonts.bodyRegular.widthOfTextAtSize(
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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[],
|
||||
startX: number,
|
||||
startY: number,
|
||||
maxWidth: number,
|
||||
fonts: EmbeddedFonts,
|
||||
): number {
|
||||
if (items.length === 0) return startY - TEXT_LINE_HEIGHT
|
||||
const sepW = separatorWidth(fonts)
|
||||
const sepBaselineOffset = (SEPARATOR_SIZE - SECTION_TEXT_SIZE) * 0.3
|
||||
let x = startX
|
||||
let y = startY
|
||||
for (let i = 0; i < items.length; i += 1) {
|
||||
const item = items[i]!
|
||||
const itemW = fonts.bodyRegular.widthOfTextAtSize(item, SECTION_TEXT_SIZE)
|
||||
if (x + itemW > startX + maxWidth && x > startX) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
page.drawText(item, {
|
||||
x,
|
||||
y,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
x += itemW
|
||||
if (i < items.length - 1) {
|
||||
if (x + sepW > startX + maxWidth) {
|
||||
x = startX
|
||||
y -= TEXT_LINE_HEIGHT
|
||||
} else {
|
||||
page.drawText(SEPARATOR_GLYPH, {
|
||||
x: x + SEPARATOR_SIDE_GAP,
|
||||
y: y - sepBaselineOffset,
|
||||
size: SEPARATOR_SIZE,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
x += sepW
|
||||
}
|
||||
}
|
||||
}
|
||||
return y - TEXT_LINE_HEIGHT
|
||||
}
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg'
|
||||
const HALO_FILTER_ID = 'osteo-halo'
|
||||
|
||||
/**
|
||||
* Adds a Gaussian-blur "halo" filter so the highlighted markers stay
|
||||
* visible on the whole-animal view once rasterised at print scale.
|
||||
*/
|
||||
function ensureHaloFilter(root: SVGSVGElement): void {
|
||||
const doc = root.ownerDocument
|
||||
if (root.querySelector(`#${HALO_FILTER_ID}`)) return
|
||||
let defs = root.querySelector('defs')
|
||||
if (!defs) {
|
||||
defs = doc.createElementNS(SVG_NS, 'defs')
|
||||
root.insertBefore(defs, root.firstChild)
|
||||
}
|
||||
const filter = doc.createElementNS(SVG_NS, 'filter')
|
||||
filter.setAttribute('id', HALO_FILTER_ID)
|
||||
filter.setAttribute('x', '-100%')
|
||||
filter.setAttribute('y', '-100%')
|
||||
filter.setAttribute('width', '300%')
|
||||
filter.setAttribute('height', '300%')
|
||||
filter.setAttribute('filterUnits', 'userSpaceOnUse')
|
||||
const wide = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
wide.setAttribute('in', 'SourceGraphic')
|
||||
wide.setAttribute('stdDeviation', '18')
|
||||
wide.setAttribute('result', 'haloWide')
|
||||
filter.appendChild(wide)
|
||||
const tight = doc.createElementNS(SVG_NS, 'feGaussianBlur')
|
||||
tight.setAttribute('in', 'SourceGraphic')
|
||||
tight.setAttribute('stdDeviation', '8')
|
||||
tight.setAttribute('result', 'haloTight')
|
||||
filter.appendChild(tight)
|
||||
const merge = doc.createElementNS(SVG_NS, 'feMerge')
|
||||
for (const input of [
|
||||
'haloWide',
|
||||
'haloWide',
|
||||
'haloWide',
|
||||
'haloTight',
|
||||
'haloTight',
|
||||
'SourceGraphic',
|
||||
]) {
|
||||
const n = doc.createElementNS(SVG_NS, 'feMergeNode')
|
||||
n.setAttribute('in', input)
|
||||
merge.appendChild(n)
|
||||
}
|
||||
filter.appendChild(merge)
|
||||
defs.appendChild(filter)
|
||||
}
|
||||
|
||||
/**
|
||||
* The view rendered from the sheet with the observation's zones of that
|
||||
* view highlighted (legacy picture: accent fill, halo on the main view,
|
||||
* other markers hidden, no data attributes left).
|
||||
*/
|
||||
export function highlightedViewSvg(
|
||||
sheet: SheetIndex,
|
||||
viewId: string,
|
||||
observation: Observation,
|
||||
): string {
|
||||
const selected = new Set(
|
||||
observation.zones
|
||||
.filter((z) => z.viewId === viewId)
|
||||
.map((z) => z.annotationId),
|
||||
)
|
||||
const root = buildViewSvg(sheet, viewId, new Map())
|
||||
const applyHalo = sheet.view(viewId)?.kind === 'main'
|
||||
if (applyHalo) ensureHaloFilter(root)
|
||||
root.querySelectorAll<Element>('[data-anno-id]').forEach((el) => {
|
||||
if (selected.has(el.getAttribute('data-anno-id') ?? '')) {
|
||||
el.setAttribute('fill', '#b85a3f')
|
||||
el.setAttribute('fill-opacity', '0.85')
|
||||
if (applyHalo) el.setAttribute('filter', `url(#${HALO_FILTER_ID})`)
|
||||
} else {
|
||||
el.setAttribute('display', 'none')
|
||||
}
|
||||
Array.from(el.attributes)
|
||||
.filter((a) => a.name.startsWith('data-'))
|
||||
.forEach((a) => el.removeAttribute(a.name))
|
||||
})
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
/** Parameters needed to render one observation page. */
|
||||
export interface ObservationPageContext {
|
||||
pdfDoc: PDFDocument
|
||||
report: Report
|
||||
observation: Observation
|
||||
obsIndex: number
|
||||
fonts: EmbeddedFonts
|
||||
sheet: SheetIndex
|
||||
locale: Locale
|
||||
headerAssets: HeaderAssets
|
||||
}
|
||||
|
||||
interface PageDrawContext {
|
||||
page: PDFPage
|
||||
fonts: EmbeddedFonts
|
||||
width: number
|
||||
}
|
||||
|
||||
interface RenderedImage {
|
||||
label: string
|
||||
img: PDFImage
|
||||
aspect: number
|
||||
}
|
||||
|
||||
interface ObservationSection {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
function drawObservationTitleBlock(
|
||||
ctx: PageDrawContext,
|
||||
dict: Dict,
|
||||
obsIndex: number,
|
||||
severity: Severity | undefined,
|
||||
): number {
|
||||
const { page, fonts } = ctx
|
||||
const { height } = page.getSize()
|
||||
const eyebrowY = height - EYEBROW_Y_OFFSET
|
||||
const titleY = height - TITLE_Y_OFFSET
|
||||
const obsLabel = String(obsIndex + 1).padStart(2, '0')
|
||||
page.drawText(dict['pdf.eyebrow.observation']!, {
|
||||
x: MARGIN_X,
|
||||
y: eyebrowY,
|
||||
size: 9,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
page.drawText(obsLabel, {
|
||||
x: MARGIN_X,
|
||||
y: titleY,
|
||||
size: 22,
|
||||
font: fonts.headingRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
if (severity) {
|
||||
const numW = fonts.headingRegular.widthOfTextAtSize(obsLabel, 22)
|
||||
const sevText = (dict[`severity.${severity}`] ?? severity).toUpperCase()
|
||||
const sevSize = 9
|
||||
const padX = 8
|
||||
const padY = 4
|
||||
const pillW = fonts.bodyBold.widthOfTextAtSize(sevText, sevSize) + padX * 2
|
||||
const pillH = sevSize + padY * 2
|
||||
const pillX = MARGIN_X + numW + 14
|
||||
const pillY = titleY + 4
|
||||
page.drawRectangle({
|
||||
x: pillX,
|
||||
y: pillY,
|
||||
width: pillW,
|
||||
height: pillH,
|
||||
color: SEVERITY_BG[severity] ?? COLOR_MUTED,
|
||||
})
|
||||
page.drawText(sevText, {
|
||||
x: pillX + padX,
|
||||
y: pillY + padY,
|
||||
size: sevSize,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_WHITE,
|
||||
})
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
/** Every view the observation touches, main first, each rasterised with its highlights. */
|
||||
async function buildObservationImages(
|
||||
pdfDoc: PDFDocument,
|
||||
sheet: SheetIndex,
|
||||
observation: Observation,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): Promise<RenderedImage[]> {
|
||||
const viewIds = [...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),
|
||||
)
|
||||
return Promise.all(
|
||||
viewIds.map(async (viewId) => {
|
||||
const view = sheet.view(viewId)!
|
||||
const label =
|
||||
view.kind === 'main'
|
||||
? dict['pdf.view.general']!
|
||||
: `${dict['pdf.view.detail_prefix']}${pickLabel(view.name, locale).toUpperCase()}`
|
||||
const png = await rasterizeSvg(
|
||||
highlightedViewSvg(sheet, viewId, observation),
|
||||
)
|
||||
const img = await pdfDoc.embedPng(png)
|
||||
return {
|
||||
label,
|
||||
img,
|
||||
aspect: img.width > 0 ? img.height / img.width : 0.6,
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function zoneText(z: ReportZone, sheet: SheetIndex, locale: Locale): 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 describeObservationZones(
|
||||
zones: ReportZone[],
|
||||
sheet: SheetIndex,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): string {
|
||||
return zones
|
||||
.map((z) => {
|
||||
const v = z.vertebrae?.length
|
||||
? ` (${z.vertebrae.map((x) => `${x.region}${x.index}`).join(', ')})`
|
||||
: ''
|
||||
const side = z.side
|
||||
? ` (${dict[z.side === 'left' ? 'lateral.left' : 'lateral.right']})`
|
||||
: ''
|
||||
return `${zoneText(z, sheet, locale)}${v}${side}`
|
||||
})
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
function findingZoneName(
|
||||
zoneId: string,
|
||||
sheet: SheetIndex,
|
||||
locale: Locale,
|
||||
): string {
|
||||
const zone = sheet.findingZone(zoneId)
|
||||
return zone ? pickLabel(zone.name, locale) : zoneId
|
||||
}
|
||||
|
||||
/** Groups findings by zone+side, one section per group; snapshots give the text. */
|
||||
function buildFindingsSections(
|
||||
findings: Finding[],
|
||||
sheet: SheetIndex,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): 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, locale)
|
||||
if (side)
|
||||
zoneName = `${zoneName} (${dict[side === 'left' ? 'lateral.left' : 'lateral.right']})`
|
||||
const value = group
|
||||
.map((f) => {
|
||||
const lbl = locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot
|
||||
return f.requiresVetReferral ? `(!) ${lbl}` : lbl
|
||||
})
|
||||
.join(' · ')
|
||||
sections.push({
|
||||
label: `${dict['pdf.section.findings_prefix']}${zoneName.toUpperCase()}`,
|
||||
value,
|
||||
})
|
||||
}
|
||||
return sections
|
||||
}
|
||||
|
||||
function buildObservationSections(
|
||||
observation: Observation,
|
||||
sheet: SheetIndex,
|
||||
locale: Locale,
|
||||
dict: Dict,
|
||||
): ObservationSection[] {
|
||||
const zonesText = describeObservationZones(
|
||||
observation.zones,
|
||||
sheet,
|
||||
locale,
|
||||
dict,
|
||||
)
|
||||
const sections: ObservationSection[] = [
|
||||
{
|
||||
label: dict['pdf.section.zones']!,
|
||||
value: zonesText || dict['pdf.empty']!,
|
||||
},
|
||||
...buildFindingsSections(observation.findings, sheet, locale, dict),
|
||||
]
|
||||
if (observation.freeTextFindings.length) {
|
||||
sections.push({
|
||||
label: dict['pdf.section.free_findings']!,
|
||||
value: observation.freeTextFindings.join(' · '),
|
||||
})
|
||||
}
|
||||
if (observation.severity) {
|
||||
sections.push({
|
||||
label: dict['pdf.section.severity']!,
|
||||
value: dict[`severity.${observation.severity}`] ?? observation.severity,
|
||||
})
|
||||
}
|
||||
if (observation.comment.trim()) {
|
||||
sections.push({
|
||||
label: dict['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(' · ')
|
||||
? countSegmentedLines(value.split(' · '), 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
|
||||
}
|
||||
|
||||
/** Lays out the (up to 2-column) image grid; returns the cursor y below it. */
|
||||
function drawObservationImageGrid(
|
||||
ctx: PageDrawContext,
|
||||
rendered: RenderedImage[],
|
||||
startY: number,
|
||||
reservedBottom: number,
|
||||
): number {
|
||||
const { page, fonts, width } = ctx
|
||||
let cursorY = startY
|
||||
if (rendered.length === 0) return cursorY
|
||||
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
|
||||
const singleOffsetX = isSingle ? (fullCellW - cellW) / 2 : 0
|
||||
const availH = Math.max(IMAGE_MIN_CELL_H, cursorY - reservedBottom)
|
||||
const rowBudget = Math.max(
|
||||
IMAGE_MIN_CELL_H,
|
||||
(availH - rows * IMAGE_LABEL_GAP - (rows - 1) * IMAGE_ROW_GAP) / rows,
|
||||
)
|
||||
for (let r = 0; r < rows; r += 1) {
|
||||
const rowItems = rendered.slice(r * cols, r * cols + cols)
|
||||
const cellHs = rowItems.map((it) => Math.min(cellW * it.aspect, rowBudget))
|
||||
const rowH = Math.max(0, ...cellHs)
|
||||
rowItems.forEach((it, c) => {
|
||||
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
||||
page.drawText(it.label, {
|
||||
x,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
})
|
||||
cursorY -= IMAGE_LABEL_GAP
|
||||
rowItems.forEach((it, c) => {
|
||||
const x = MARGIN_X + singleOffsetX + c * (cellW + IMAGE_COL_GAP)
|
||||
page.drawImage(it.img, {
|
||||
x,
|
||||
y: cursorY - cellHs[c]!,
|
||||
width: cellW,
|
||||
height: cellHs[c]!,
|
||||
})
|
||||
})
|
||||
cursorY -= rowH
|
||||
if (r < rows - 1) cursorY -= IMAGE_ROW_GAP
|
||||
}
|
||||
cursorY -= IMAGE_BOTTOM_GAP
|
||||
return cursorY
|
||||
}
|
||||
|
||||
function drawObservationSections(
|
||||
ctx: PageDrawContext,
|
||||
sections: ObservationSection[],
|
||||
startY: number,
|
||||
maxTextW: number,
|
||||
): number {
|
||||
const { page, fonts } = ctx
|
||||
let cursorY = startY
|
||||
for (const { label, value } of sections) {
|
||||
page.drawText(label, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: 8,
|
||||
font: fonts.bodyBold,
|
||||
color: COLOR_ACCENT,
|
||||
})
|
||||
cursorY -= SECTION_LABEL_GAP + 9
|
||||
if (value.includes(' · ')) {
|
||||
cursorY = drawSegmentedText(
|
||||
page,
|
||||
value.split(' · '),
|
||||
MARGIN_X,
|
||||
cursorY,
|
||||
maxTextW,
|
||||
fonts,
|
||||
)
|
||||
} else {
|
||||
for (const line of wrapLines(
|
||||
value,
|
||||
fonts.bodyRegular,
|
||||
SECTION_TEXT_SIZE,
|
||||
maxTextW,
|
||||
)) {
|
||||
page.drawText(line, {
|
||||
x: MARGIN_X,
|
||||
y: cursorY,
|
||||
size: SECTION_TEXT_SIZE,
|
||||
font: fonts.bodyRegular,
|
||||
color: COLOR_INK,
|
||||
})
|
||||
cursorY -= TEXT_LINE_HEIGHT
|
||||
}
|
||||
}
|
||||
cursorY -= SECTION_BLOCK_GAP
|
||||
}
|
||||
return cursorY
|
||||
}
|
||||
|
||||
export async function addObservationPage(
|
||||
ctx: ObservationPageContext,
|
||||
): Promise<void> {
|
||||
const {
|
||||
pdfDoc,
|
||||
report,
|
||||
observation,
|
||||
obsIndex,
|
||||
fonts,
|
||||
sheet,
|
||||
locale,
|
||||
headerAssets,
|
||||
} = ctx
|
||||
const dict = getDict(locale)
|
||||
const page = pdfDoc.addPage(PageSizes.A4)
|
||||
const { width } = page.getSize()
|
||||
drawHeader(page, report, fonts, locale, headerAssets)
|
||||
|
||||
const drawCtx: PageDrawContext = { page, fonts, width }
|
||||
const titleY = drawObservationTitleBlock(
|
||||
drawCtx,
|
||||
dict,
|
||||
obsIndex,
|
||||
observation.severity,
|
||||
)
|
||||
const rendered = await buildObservationImages(
|
||||
pdfDoc,
|
||||
sheet,
|
||||
observation,
|
||||
locale,
|
||||
dict,
|
||||
)
|
||||
const maxTextW = width - MARGIN_X * 2
|
||||
const sections = buildObservationSections(observation, sheet, locale, dict)
|
||||
const reservedBottom =
|
||||
MARGIN_BOTTOM +
|
||||
estimateSectionsHeight(sections, fonts, maxTextW) +
|
||||
IMAGE_BOTTOM_GAP
|
||||
let cursorY = drawObservationImageGrid(
|
||||
drawCtx,
|
||||
rendered,
|
||||
titleY - IMAGE_TOP_GAP,
|
||||
reservedBottom,
|
||||
)
|
||||
cursorY -= TEXT_TOP_GAP
|
||||
drawObservationSections(drawCtx, sections, cursorY, maxTextW)
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
const TARGET_WIDTH = 1200
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
function startsWithPngSignature(bytes: Uint8Array): boolean {
|
||||
if (bytes.length < PNG_SIGNATURE.length) return false
|
||||
for (let i = 0; i < PNG_SIGNATURE.length; i += 1) {
|
||||
if (bytes[i] !== PNG_SIGNATURE[i]) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function ensureSvgAttributes(
|
||||
svgString: string,
|
||||
widthPx: number,
|
||||
heightPx: number,
|
||||
): string {
|
||||
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
if (root.namespaceURI !== 'http://www.w3.org/2000/svg') {
|
||||
// Some serializers strip xmlns; force the SVG namespace so
|
||||
// browsers will rasterize the blob URL as an image.
|
||||
root.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
|
||||
}
|
||||
if (!root.getAttribute('width')) root.setAttribute('width', String(widthPx))
|
||||
if (!root.getAttribute('height'))
|
||||
root.setAttribute('height', String(heightPx))
|
||||
return new XMLSerializer().serializeToString(root)
|
||||
}
|
||||
|
||||
function readViewBox(svgString: string): {
|
||||
widthPx: number
|
||||
heightPx: number
|
||||
} {
|
||||
const doc = new DOMParser().parseFromString(svgString, 'image/svg+xml')
|
||||
const vb = (doc.documentElement.getAttribute('viewBox') ?? '0 0 1000 600')
|
||||
.split(/\s+/)
|
||||
.map(Number)
|
||||
const ratio = vb[3] > 0 && vb[2] > 0 ? vb[3] / vb[2] : 0.6
|
||||
const widthPx = Math.max(1, Math.round(TARGET_WIDTH))
|
||||
const heightPx = Math.max(1, Math.round(ratio * widthPx))
|
||||
return { widthPx, heightPx }
|
||||
}
|
||||
|
||||
async function rasterizeWithImageElement(
|
||||
svgString: string,
|
||||
widthPx: number,
|
||||
heightPx: number,
|
||||
): Promise<HTMLCanvasElement> {
|
||||
const normalized = ensureSvgAttributes(svgString, widthPx, heightPx)
|
||||
const svgBlob = new Blob([normalized], {
|
||||
type: 'image/svg+xml;charset=utf-8',
|
||||
})
|
||||
const url = URL.createObjectURL(svgBlob)
|
||||
const img = new Image()
|
||||
img.decoding = 'sync'
|
||||
img.crossOrigin = 'anonymous'
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
img.onload = () => resolve()
|
||||
img.onerror = () =>
|
||||
reject(new Error('Browser failed to render the SVG into an Image'))
|
||||
img.src = url
|
||||
})
|
||||
} finally {
|
||||
// The Blob URL is single-use — release it once the Image has loaded
|
||||
// (or failed).
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = widthPx
|
||||
canvas.height = heightPx
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Canvas 2D context unavailable')
|
||||
ctx.fillStyle = '#ffffff'
|
||||
ctx.fillRect(0, 0, widthPx, heightPx)
|
||||
ctx.drawImage(img, 0, 0, widthPx, heightPx)
|
||||
return canvas
|
||||
}
|
||||
|
||||
async function canvasToPngBytes(
|
||||
canvas: HTMLCanvasElement,
|
||||
): Promise<Uint8Array> {
|
||||
const blob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob((b) => resolve(b), 'image/png')
|
||||
})
|
||||
if (blob) {
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer())
|
||||
if (startsWithPngSignature(bytes)) return bytes
|
||||
}
|
||||
const dataUrl = canvas.toDataURL('image/png')
|
||||
if (!dataUrl.startsWith('data:image/png')) {
|
||||
throw new Error(
|
||||
`canvas.toDataURL produced non-PNG payload: ${dataUrl.slice(0, 32)}`,
|
||||
)
|
||||
}
|
||||
const comma = dataUrl.indexOf(',')
|
||||
if (comma < 0) {
|
||||
throw new Error('canvas.toDataURL returned a data URL without a payload')
|
||||
}
|
||||
const binary = atob(dataUrl.slice(comma + 1))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i += 1) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
if (!startsWithPngSignature(bytes)) {
|
||||
throw new Error('canvas.toDataURL produced bytes without a PNG signature')
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Rasterizes an SVG string to a PNG byte array using the browser's native
|
||||
* SVG-to-Image pipeline. The browser parses + draws the SVG via an
|
||||
* Image/Blob URL pair, which renders identically to what the user sees in
|
||||
* the inline anatomy canvas.
|
||||
*
|
||||
* @param svgString Serialized SVG (must declare `xmlns`)
|
||||
*/
|
||||
export async function rasterizeSvg(svgString: string): Promise<Uint8Array> {
|
||||
const { widthPx, heightPx } = readViewBox(svgString)
|
||||
const canvas = await rasterizeWithImageElement(svgString, widthPx, heightPx)
|
||||
return canvasToPngBytes(canvas)
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import type { PDFFont } from 'pdf-lib'
|
||||
|
||||
/**
|
||||
* Greedy word-wrap: splits `text` into lines whose rendered width at
|
||||
* `size` points stays within `max` for the given font.
|
||||
*/
|
||||
export function wrapLines(
|
||||
text: string,
|
||||
font: PDFFont,
|
||||
size: number,
|
||||
max: number,
|
||||
): string[] {
|
||||
const words = text.split(/\s+/)
|
||||
const lines: string[] = []
|
||||
let line = ''
|
||||
for (const w of words) {
|
||||
const test = line ? `${line} ${w}` : w
|
||||
if (font.widthOfTextAtSize(test, size) > max && line) {
|
||||
lines.push(line)
|
||||
line = w
|
||||
} else {
|
||||
line = test
|
||||
}
|
||||
}
|
||||
if (line) lines.push(line)
|
||||
return lines
|
||||
}
|
||||
Reference in new issue
Block a user