NTP_V2/web/src/lib/pdf.ts

50 lines
2.4 KiB
TypeScript

/**
* Render a DOM element to an A5 PDF in the browser and return an object URL for it.
* html2canvas rasterises the element, so Arabic shaping / RTL and the page fonts come out exactly as on screen
* (text in the PDF is an image, not selectable). Both libraries are loaded on demand, only when a PDF is made.
* Always rendered black on white, whatever the current theme.
*/
export type PdfOrientation = 'portrait' | 'landscape';
export async function elementToPdfUrl(el: HTMLElement, orientation: PdfOrientation): Promise<string> {
const [{ default: html2canvas }, { jsPDF }] = await Promise.all([import('html2canvas'), import('jspdf')]);
// let web fonts (Cairo) finish loading so the capture does not fall back to a system font
if ('fonts' in document) await (document as Document & { fonts: FontFaceSet }).fonts.ready;
const canvas = await html2canvas(el, {
scale: 2,
backgroundColor: '#ffffff',
useCORS: true,
logging: false,
onclone: (doc, cloned) => {
// print is always light: neutralise the dark theme / paper colours in the cloned tree only
const root = cloned as HTMLElement;
// any letter-spacing makes html2canvas draw Arabic letter by letter, which breaks the joining: keep the default
root.style.letterSpacing = 'normal';
root.querySelectorAll<HTMLElement>('*').forEach((n) => { n.style.letterSpacing = 'normal'; });
// a sheet designed black-on-white (the legacy slips) keeps its own colours and borders
if (root.hasAttribute('data-pdf-literal')) { void doc; return; }
root.style.background = '#ffffff';
root.style.boxShadow = 'none';
root.style.color = '#000000';
root.querySelectorAll<HTMLElement>('*').forEach((n) => {
n.style.color = '#000000';
if (getComputedStyle(n).backgroundColor !== 'rgba(0, 0, 0, 0)') n.style.backgroundColor = '#ffffff';
n.style.borderColor = '#999999';
});
void doc;
},
});
const pdf = new jsPDF({ unit: 'mm', format: 'a5', orientation });
const pageW = pdf.internal.pageSize.getWidth();
const pageH = pdf.internal.pageSize.getHeight();
const margin = 6;
const ratio = Math.min((pageW - margin * 2) / canvas.width, (pageH - margin * 2) / canvas.height);
const w = canvas.width * ratio;
const h = canvas.height * ratio;
pdf.addImage(canvas.toDataURL('image/jpeg', 0.95), 'JPEG', (pageW - w) / 2, margin, w, h);
return URL.createObjectURL(pdf.output('blob'));
}