If you generate anything that has to be printed at an exact physical size (passport photos, labels, stickers, name badges), you hit two problems that screen work never prepares you for:
- Your layout has to be in millimetres, not pixels, and it must never "shrink to fit".
- The file has to tell the printer its physical size, or it opens at whatever DPI the viewer guesses (usually 72 or 96) and prints at the wrong size.
I ran into both while building a print-sheet tool for passport photos, where a 35 × 45 mm photo printed at 33 × 43 mm is simply rejected. Here's how the layout and the file density are handled, with the actual code.
1. Work in millimetres, convert once
Every length in the layout is in mm. Pixels only appear at render time, at a fixed 300 ppi:
export const SHEET_PPI = 300; export const mmToPx = (mm: number, ppi = SHEET_PPI) => Math.round((mm / 25.4) * ppi); A 35 × 45 mm photo becomes 413 × 531 px; a 4 × 6 in sheet (152.4 × 101.6 mm) becomes 1800 × 1200 px. Keeping the whole layout in mm means the browser preview and the server renderer share one pure function and can't disagree.
Paper sizes are just data:
export const PAPERS = { "4x6": { label: "4 × 6 in", width: 152.4, height: 101.6 }, "5x7": { label: "5 × 7 in", width: 177.8, height: 127 }, a4: { label: "A4", width: 210, height: 297 }, letter: { label: "US Letter", width: 215.9, height: 279.4 }, } as const; 2. A grid that never shrinks the photos
The tempting approach is "fit N photos on the page" and scale them down. For documents with a mandated size that's exactly wrong. Instead the photo size is fixed, and the question becomes "how many fit, with fixed margins and gaps?"
With margin m and gap g, the number of columns that fit across width W for photo width w is:
cols = floor((W - 2m + g) / (w + g)) The + g is there because n photos only need n - 1 gaps. Same for rows. Then centre the block that's actually used:
export function printLayout( paperW: number, paperH: number, photoW: number, photoH: number, copies: number, margin = 3, gap = 3, ) { const cols = Math.floor((paperW - 2 * margin + gap) / (photoW + gap)); const rows = Math.floor((paperH - 2 * margin + gap) / (photoH + gap)); const capacity = cols * rows; if (cols < 1 || rows < 1 || copies > capacity) return null; const usedCols = Math.min(cols, copies); const usedRows = Math.ceil(copies / cols); const left = (paperW - (usedCols * photoW + (usedCols - 1) * gap)) / 2; const top = (paperH - (usedRows * photoH + (usedRows - 1) * gap)) / 2; return { capacity, positions: Array.from({ length: copies }, (_, i) => ({ x: left + (i % cols) * (photoW + gap), y: top + Math.floor(i / cols) * (photoH + gap), })), }; } It returns null rather than a degraded layout when the request can't be met, so the UI can say "max N copies on this paper" instead of quietly producing something wrong. The 3 mm gap also leaves room for cut guides.
Because it's pure (no DOM, no Node APIs), it's trivially unit-tested, and the same function drives the live <canvas> preview in the browser and the final render on the server.
3. Validate the spec like any other untrusted input
The customer's choices (paper, photo size, copies, crop) travel from the browser to checkout and then to the renderer. Treat that object as hostile: check types, ranges and that the crop rectangle stays inside the image, and finally run it through printLayout so a spec that passes validation is guaranteed to render:
const paper = PAPERS[spec.paper]; return printLayout(paper.width, paper.height, spec.widthMm, spec.heightMm, spec.copies) ? spec : null; Storing the crop as fractions of the source image (0–1) rather than pixels also means it survives any re-encoding or resizing of the uploaded photo.
4. Write the DPI into the PNG
This is the step most people miss. A PNG made with canvas.toBlob() or most server image libraries has no physical size. Open it in a print dialog and the OS picks a default DPI, and your carefully measured 35 mm becomes something else.
PNG stores physical density in an optional pHYs chunk: pixels per metre on each axis, plus a unit byte (1 = metre). 300 ppi is 300 / 0.0254 ≈ 11811 px/m. The chunk has to come after IHDR and before the image data, and like every PNG chunk it ends with a CRC-32 over its type and data.
export function withPngDensity(png: Uint8Array, dpi: number): Uint8Array { const density = Math.round(dpi / 0.0254); // length(4) + "pHYs"(4) + x(4) + y(4) + unit(1) + crc(4) = 21 bytes const chunk = new Uint8Array(21); const view = new DataView(chunk.buffer); view.setUint32(0, 9); // data length chunk.set([112, 72, 89, 115], 4); // "pHYs" view.setUint32(8, density); // x px per metre view.setUint32(12, density); // y px per metre chunk[16] = 1; // unit: metre let crc = 0xffffffff; // CRC-32 over type + data for (const byte of chunk.slice(4, 17)) { crc ^= byte; for (let b = 0; b < 8; b++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); } view.setUint32(17, (crc ^ 0xffffffff) >>> 0); // Walk the chunks: drop any existing pHYs, insert ours right after IHDR. // (signature check, bounds checks and IEND handling omitted here) ... } No dependency, no re-encoding, and the pixels are untouched: you only splice 21 bytes into the file. After this, "Print at 100 %" / "Actual size" in any normal print dialog gives you real millimetres. JPEG has the equivalent in its JFIF header (density units + X/Y density) if you need that instead.
5. Tell the user how to print it
Even with correct metadata, "Fit to page" in a print dialog will scale the image. The UI copy matters as much as the code: tell people to print at 100 % or "actual size", or better, to order a normal 4 × 6 in photo print, which every pharmacy kiosk prints at true size.
Takeaways
- Keep physical layouts in mm and convert to px in one place.
- Compute capacity with
floor((W - 2m + g) / (w + g)), never scale to fit. - Make the layout function pure so preview and render can't drift.
- Return
nullfor impossible specs instead of degrading silently. - Write
pHYs(PNG) or JFIF density (JPEG) so the file prints at its real size.
If you want to see it working, this is the passport photo print sheet tool it comes from. Disclosure: it's my own site; the preview is free and the downloaded sheet is paid.
This post was drafted with help from an AI assistant and checked against the production code.

