import { Built } from './dxf-geometry'; import { Box, exportBox, needsRasterText, paddedBox, sheetSvg } from './export-svg'; import { ColorMode } from './render'; import { Sheet } from './scene'; import { importUrl } from '../shared/import-url'; import { vendored } from '../shared/vendor'; /** * DWG to PDF: page sizes, plot scales and how a tab is laid out on a page, * then the PDF itself, drawn as vectors by jsPDF and svg2pdf.js (both MIT, * served from this site) from the same SVG as the .svg download. */ const JSPDF = vendored('jspdf@4.2.1/+esm'); const SVG2PDF = vendored('svg2pdf.js@2.8.1/+esm'); export interface PaperSize { id: string; label: string; /** Portrait, in millimetres. */ w: number; h: number; } const IN = 25.4; export const PAPER_SIZES: PaperSize[] = [ { id: 'a4', label: 'A4 (210 × 297 mm)', w: 210, h: 297 }, { id: 'a3', label: 'A3 (297 × 420 mm)', w: 297, h: 420 }, { id: 'a2', label: 'A2 (420 × 594 mm)', w: 420, h: 594 }, { id: 'a1', label: 'A1 (594 × 841 mm)', w: 594, h: 841 }, { id: 'a0', label: 'A0 (841 × 1189 mm)', w: 841, h: 1189 }, { id: 'letter', label: 'Letter (8.5 × 11 in)', w: 8.5 * IN, h: 11 * IN }, { id: 'legal', label: 'Legal (8.5 × 14 in)', w: 8.5 * IN, h: 14 * IN }, { id: 'tabloid', label: 'Tabloid / ANSI B (11 × 17 in)', w: 11 * IN, h: 17 * IN }, { id: 'ansi-c', label: 'ANSI C (17 × 22 in)', w: 17 * IN, h: 22 * IN }, { id: 'ansi-d', label: 'ANSI D (22 × 34 in)', w: 22 * IN, h: 34 * IN }, { id: 'ansi-e', label: 'ANSI E (34 × 44 in)', w: 34 * IN, h: 44 * IN }, { id: 'arch-c', label: 'Arch C (18 × 24 in)', w: 18 * IN, h: 24 * IN }, { id: 'arch-d', label: 'Arch D (24 × 36 in)', w: 24 * IN, h: 36 * IN }, { id: 'arch-e1', label: 'Arch E1 (30 × 42 in)', w: 30 * IN, h: 42 * IN }, ]; export interface PlotScale { /** 1:N - a length on paper is the real length divided by N. */ n: number; label: string; group: 'Metric' | 'Architectural (inches to feet)' | 'Engineering (inches to feet)'; } const metric = [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 1250, 2000, 2500, 5000, 10000]; export const PLOT_SCALES: PlotScale[] = [ ...[1 / 10, 1 / 5, 1 / 2].map((n) => ({ n, label: `${1 / n}:1`, group: 'Metric' as const })), ...metric.map((n) => ({ n, label: `1:${n}`, group: 'Metric' as const })), // Architectural: so many inches of paper to a foot of building; 1/4" = 1'-0" is 1:48. ...([['1/16"', 1 / 16], ['3/32"', 3 / 32], ['1/8"', 1 / 8], ['3/16"', 3 / 16], ['1/4"', 1 / 4], ['3/8"', 3 / 8], ['1/2"', 1 / 2], ['3/4"', 3 / 4], ['1"', 1], ['1 1/2"', 1.5], ['3"', 3], ['6"', 6], ['12"', 12]] as [string, number][]) .map(([t, inches]) => ({ n: 12 / inches, label: `${t} = 1'-0"`, group: 'Architectural (inches to feet)' as const })), // Engineering: one inch of paper to so many feet; 1" = 20' is 1:240. ...[10, 20, 30, 40, 50, 60, 100, 200, 500, 1000].map((ft) => ({ n: ft * 12, label: `1" = ${ft}'`, group: 'Engineering (inches to feet)' as const })), ]; export interface PdfOptions { paper: string; orientation: 'auto' | 'portrait' | 'landscape'; marginMm: number; /** 'fit', or N for 1:N. */ scale: 'fit' | number; /** Millimetres in one drawing unit, for a plot scale. */ unitMm: number; color: ColorMode; lineweights: boolean; } export interface PagePlan { /** The page, in millimetres. */ pageW: number; pageH: number; /** Millimetres of paper per sheet unit. */ mmPerUnit: number; /** The area of the sheet that is drawn, and where its top left corner goes on the page (millimetres from the top left). */ box: Box; x: number; y: number; /** What the page is, for the reader: "A3 landscape, 1:50". */ label: string; } /** * Where a tab goes on paper. A layout with a page setup is its own page at * 1:1. Anything else goes on the chosen paper, fitted inside the margins or at * a plot scale; a drawing too big for the paper at that scale is an error * that says so, never quietly shrunk. */ export function planPage(sheet: Sheet, o: PdfOptions): PagePlan | { error: string } { const p = sheet.paper; if (p) { const box = exportBox(sheet); return { pageW: p.widthMm, pageH: p.heightMm, mmPerUnit: p.mmPerUnit, box, x: 0, y: 0, label: `${sizeText(p.widthMm, p.heightMm)}, the layout’s own page, 1:1` }; } const paper = PAPER_SIZES.find((s) => s.id === o.paper) ?? PAPER_SIZES[0]; const ext: Box = { minX: sheet.minX, minY: sheet.minY, maxX: sheet.maxX, maxY: sheet.maxY }; if (!(ext.maxX >= ext.minX && ext.maxY >= ext.minY)) return { error: 'There is nothing on this tab to print.' }; const m = Math.max(0, o.marginMm); const orient = (land: boolean) => (land ? [paper.h, paper.w] : [paper.w, paper.h]); if (o.scale === 'fit') { const box = paddedBox(ext); const w = box.maxX - box.minX, h = box.maxY - box.minY; const land = o.orientation === 'landscape' || (o.orientation === 'auto' && w >= h); const [pw, ph] = orient(land); if (pw - 2 * m <= 0 || ph - 2 * m <= 0) return { error: 'The margins leave no room on the paper.' }; const k = Math.min((pw - 2 * m) / w, (ph - 2 * m) / h); return { pageW: pw, pageH: ph, mmPerUnit: k, box, x: (pw - w * k) / 2, y: (ph - h * k) / 2, label: `${paper.label.split(' (')[0]} ${land ? 'landscape' : 'portrait'}, fitted (about 1:${roundScale(o.unitMm > 0 ? o.unitMm / k : 0)})` }; } if (!(o.unitMm > 0)) return { error: 'The drawing does not say what its units are, so a scale cannot be worked out. Choose its units under "1 drawing unit is", or choose Fit.' }; const k = o.unitMm / o.scale; const w = (ext.maxX - ext.minX) * k, h = (ext.maxY - ext.minY) * k; const fits = (land: boolean) => { const [pw, ph] = orient(land); return w <= pw - 2 * m + 1e-9 && h <= ph - 2 * m + 1e-9; }; let land: boolean; if (o.orientation === 'auto') land = fits(w >= h) ? w >= h : fits(!(w >= h)) ? !(w >= h) : w >= h; else land = o.orientation === 'landscape'; const [pw, ph] = orient(land); const scaleLabel = PLOT_SCALES.find((s) => s.n === o.scale)?.label ?? `1:${o.scale}`; const name = `${paper.label.split(' (')[0]} ${land ? 'landscape' : 'portrait'}`; if (!fits(land)) { return { error: `At ${scaleLabel} the drawing is ${sizeText(w, h)}, larger than the ${sizeText(pw - 2 * m, ph - 2 * m)} inside the margins of ${name}. Choose larger paper or a smaller scale, or Fit to make it fit.`, }; } return { pageW: pw, pageH: ph, mmPerUnit: k, box: ext, x: (pw - w) / 2, y: (ph - h) / 2, label: `${name}, ${scaleLabel}` }; } function sizeText(w: number, h: number): string { const f = (v: number) => (v >= 100 ? Math.round(v).toLocaleString('en') : (Math.round(v * 10) / 10).toLocaleString('en')); return `${f(w)} × ${f(h)} mm`; } function roundScale(n: number): string { if (!(n > 0) || !isFinite(n)) return '?'; return n >= 10 ? Math.round(n).toLocaleString('en') : n.toPrecision(2); } /** Points in a millimetre. */ const PT = 72 / 25.4; export interface PdfPage { sheet: Sheet; plan: PagePlan; } /** * The PDF: one page per tab given. Each page is vectors, except that a page * with text outside the PDF's built-in font (Western European letters) goes * in as a sharp picture so its lettering survives. */ export async function makePdf(pages: PdfPage[], model: Built, o: PdfOptions, hidden: Set, title: string): Promise { const [{ jsPDF }, { svg2pdf }] = await Promise.all([importUrl(JSPDF), importUrl(SVG2PDF)]); const first = pages[0].plan; const doc = new jsPDF({ unit: 'pt', format: [first.pageW * PT, first.pageH * PT], orientation: first.pageW > first.pageH ? 'l' : 'p', compress: true }); const holder = document.createElement('div'); holder.style.cssText = 'position:fixed;left:-100000px;top:0;overflow:hidden'; document.body.append(holder); try { for (let i = 0; i < pages.length; i++) { const { sheet, plan } = pages[i]; if (i) doc.addPage([plan.pageW * PT, plan.pageH * PT], plan.pageW > plan.pageH ? 'l' : 'p'); const bw = plan.box.maxX - plan.box.minX, bh = plan.box.maxY - plan.box.minY; const w = bw * plan.mmPerUnit * PT, h = bh * plan.mmPerUnit * PT; const x = plan.x * PT, y = plan.y * PT; const svg = sheetSvg(sheet, model, { pdf: true, mmPerUnit: plan.mmPerUnit, lineweights: o.lineweights, mode: o.color, hidden, box: plan.box }); if (needsRasterText(sheet, model)) { const png = await svgToCanvas(svg, bw, bh, 4000); doc.addImage(png, 'PNG', x, y, w, h); png.width = png.height = 0; } else { holder.innerHTML = svg; await svg2pdf(holder.firstElementChild as SVGElement, doc, { x, y, width: w, height: h }); holder.innerHTML = ''; } } doc.setProperties({ title, creator: 'johnmcm.com' }); return doc.output('blob'); } finally { holder.remove(); } } /** The SVG drawn on a canvas whose long side is `long` pixels, white behind it. */ export async function svgToCanvas(svg: string, vw: number, vh: number, long: number): Promise { const k = long / Math.max(vw, vh); const cw = Math.max(1, Math.round(vw * k)), ch = Math.max(1, Math.round(vh * k)); const sized = svg.replace('