193 lines
6.6 KiB
TypeScript
193 lines
6.6 KiB
TypeScript
import { createRoot } from 'react-dom/client';
|
||
import { createElement } from 'react';
|
||
import { NextIntlClientProvider } from 'next-intl';
|
||
import type { AbstractIntlMessages } from 'next-intl';
|
||
import { jsPDF } from 'jspdf';
|
||
import html2canvas from 'html2canvas';
|
||
import {
|
||
CaseSheetPrintLayout,
|
||
type CaseSheetLabels,
|
||
type CaseSheetOrientation,
|
||
type CaseSheetPrintedComment,
|
||
} from '@/components/ui/lab/CaseSheetPrintLayout';
|
||
import type { LabCaseDetail } from '@/types/cases';
|
||
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
|
||
|
||
type DownloadCaseSheetPdfArgs = {
|
||
labCase: LabCaseDetail;
|
||
locale: string;
|
||
messages: AbstractIntlMessages;
|
||
labels: CaseSheetLabels;
|
||
prosthesisCatalog: readonly ProsthesisCatalogEntry[];
|
||
notes?: readonly string[];
|
||
comments?: readonly CaseSheetPrintedComment[];
|
||
fileName?: string;
|
||
orientation?: CaseSheetOrientation;
|
||
organizationName: string;
|
||
};
|
||
|
||
function printFontFamily(locale: string): string {
|
||
if (locale !== 'fa' || typeof document === 'undefined') {
|
||
return 'system-ui, -apple-system, "Segoe UI", sans-serif';
|
||
}
|
||
const style = getComputedStyle(document.documentElement);
|
||
const vazir = style.getPropertyValue('--font-vazirmatn').trim();
|
||
const noto = style.getPropertyValue('--font-noto-sans-arabic').trim();
|
||
return [vazir, noto, 'Tahoma', '"Segoe UI"', 'sans-serif'].filter(Boolean).join(', ');
|
||
}
|
||
|
||
function waitForPaint(): Promise<void> {
|
||
return new Promise((resolve) => {
|
||
requestAnimationFrame(() => {
|
||
requestAnimationFrame(() => resolve());
|
||
});
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Renders an off-screen Case Sheet, captures it, and downloads an A4 PDF
|
||
* (ISO A-series √2 ratio — prints cleanly onto A3–A6).
|
||
*
|
||
* Print layout uses hex-only inline styles so html2canvas is not fed Tailwind
|
||
* `lab()` / `oklch()` from global stylesheets.
|
||
*/
|
||
export async function downloadCaseSheetPdf({
|
||
labCase,
|
||
locale,
|
||
messages,
|
||
labels,
|
||
prosthesisCatalog,
|
||
notes = [],
|
||
comments = [],
|
||
fileName,
|
||
orientation = 'portrait',
|
||
organizationName,
|
||
}: DownloadCaseSheetPdfArgs): Promise<void> {
|
||
const host = document.createElement('div');
|
||
host.setAttribute('aria-hidden', 'true');
|
||
host.style.cssText =
|
||
'position:fixed;left:-12000px;top:0;z-index:-1;pointer-events:none;opacity:1;';
|
||
document.body.appendChild(host);
|
||
|
||
const root = createRoot(host);
|
||
try {
|
||
root.render(
|
||
createElement(NextIntlClientProvider, {
|
||
locale,
|
||
messages,
|
||
children: createElement(CaseSheetPrintLayout, {
|
||
labCase,
|
||
locale,
|
||
labels,
|
||
prosthesisCatalog,
|
||
orientation,
|
||
organizationName,
|
||
notes,
|
||
comments,
|
||
fontFamily: printFontFamily(locale),
|
||
}),
|
||
}),
|
||
);
|
||
await waitForPaint();
|
||
await new Promise((r) => setTimeout(r, 80));
|
||
|
||
const sheet = host.querySelector('[data-case-sheet-root]');
|
||
if (!(sheet instanceof HTMLElement)) {
|
||
throw new Error('Case sheet root not found');
|
||
}
|
||
|
||
const canvas = await html2canvas(sheet, {
|
||
scale: 2,
|
||
backgroundColor: '#ffffff',
|
||
useCORS: true,
|
||
logging: false,
|
||
scrollX: 0,
|
||
scrollY: -window.scrollY,
|
||
// Drop app stylesheets so parsers never see lab()/oklch() from Tailwind.
|
||
onclone: (clonedDoc) => {
|
||
clonedDoc.querySelectorAll('style, link[rel="stylesheet"]').forEach((node) => {
|
||
const css = node instanceof HTMLStyleElement ? (node.textContent ?? '') : '';
|
||
if (css.includes('@font-face') && !/oklch\(|\blab\(/i.test(css)) return;
|
||
node.remove();
|
||
});
|
||
// Brand mark viewBoxes are thousands of units. Without an explicit
|
||
// pixel size, html2canvas lays them out huge and pads the page.
|
||
clonedDoc.querySelectorAll('[data-case-sheet-org]').forEach((node) => {
|
||
if (!(node instanceof HTMLElement)) return;
|
||
node.style.display = 'flex';
|
||
node.style.alignItems = 'center';
|
||
node.style.justifyContent = 'flex-start';
|
||
node.style.height = '48px';
|
||
node.style.lineHeight = '48px';
|
||
node.style.overflow = 'hidden';
|
||
node.style.direction = 'ltr';
|
||
node.style.letterSpacing = '0px';
|
||
node.style.wordSpacing = '0px';
|
||
const text = node.querySelector('[data-case-sheet-org-text]');
|
||
if (!(text instanceof HTMLElement)) return;
|
||
text.style.display = 'inline-block';
|
||
text.style.maxWidth = '100%';
|
||
text.style.overflow = 'visible';
|
||
text.style.lineHeight = '48px';
|
||
text.style.paddingTop = '0';
|
||
text.style.paddingBottom = '0';
|
||
text.style.letterSpacing = '0px';
|
||
text.style.wordSpacing = '0px';
|
||
text.style.whiteSpace = 'nowrap';
|
||
text.style.unicodeBidi = 'isolate';
|
||
});
|
||
clonedDoc.querySelectorAll('[data-case-sheet-lockup]').forEach((node) => {
|
||
if (!(node instanceof HTMLElement)) return;
|
||
node.style.height = '28px';
|
||
node.style.lineHeight = '28px';
|
||
node.style.overflow = 'hidden';
|
||
});
|
||
clonedDoc.querySelectorAll('[data-case-sheet-lockup] svg').forEach((node) => {
|
||
if (!(node instanceof SVGSVGElement)) return;
|
||
const parts = (node.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number);
|
||
const vbW = parts[2];
|
||
const vbH = parts[3];
|
||
if (!vbW || !vbH) return;
|
||
const height = 22;
|
||
const width = Math.max(1, Math.round(height * (vbW / vbH)));
|
||
node.setAttribute('width', String(width));
|
||
node.setAttribute('height', String(height));
|
||
node.style.width = `${width}px`;
|
||
node.style.height = `${height}px`;
|
||
node.style.verticalAlign = 'middle';
|
||
node.style.overflow = 'hidden';
|
||
});
|
||
},
|
||
});
|
||
|
||
const pdf = new jsPDF({
|
||
orientation,
|
||
unit: 'mm',
|
||
format: 'a4',
|
||
});
|
||
const pageWidth = pdf.internal.pageSize.getWidth();
|
||
const pageHeight = pdf.internal.pageSize.getHeight();
|
||
const margin = 4;
|
||
const usableWidth = pageWidth - margin * 2;
|
||
const usableHeight = pageHeight - margin * 2;
|
||
|
||
const imgData = canvas.toDataURL('image/png');
|
||
let drawWidth = usableWidth;
|
||
let drawHeight = (canvas.height * drawWidth) / canvas.width;
|
||
if (drawHeight > usableHeight) {
|
||
drawHeight = usableHeight;
|
||
drawWidth = (canvas.width * drawHeight) / canvas.height;
|
||
}
|
||
const x = margin + (usableWidth - drawWidth) / 2;
|
||
pdf.addImage(imgData, 'PNG', x, margin, drawWidth, drawHeight);
|
||
|
||
const safeName =
|
||
fileName ??
|
||
`case-sheet-${labCase.id.replace(/-/g, '').slice(0, 8)}.pdf`;
|
||
pdf.save(safeName);
|
||
} finally {
|
||
root.unmount();
|
||
host.remove();
|
||
}
|
||
}
|