Why Printed QR Codes Fail to Scan: Building a Pre-Download Verification Gate
Why a QR Code Fails on Paper
The utility suite I maintain for small businesses — tax calculators, e-invoice validators, PDF processors — keeps circling back to the same artefact: the QR code. A shop wants a code on a table tent, a name card, a lorry decal, a receipt. The request is always the same sentence: this code works, print it.
The honest version of that job is not drawing squares. It is handing over a file that scans on the surface it is heading for, and the two most expensive failures in this class both pass every check a browser can perform. A symbol that decodes perfectly on a 400 px canvas can be 0.29 mm per module on paper, which no phone camera centre-zone will find. A maroon code scores 10.9:1 on contrast, passes accessibility tooling without a note, and reads as blank paper to the red-LED scanner bolted to a shop counter.
So the tool I built has one non-negotiable rule: the download stays locked until jsQR decodes the symbol that is about to be exported and gets the payload back exactly. Not a preview of it — the geometry that gets written to the file, re-inked from the same vector path, read by a decoder import that is deliberately not the one the page uses for its own verdict.
The engine itself is unremarkable: six payload types (text or URL, Wi-Fi, vCard 3.0, tel:, SMSTO:, mailto:), four module shapes, three finder-pattern shapes, foreground and background plus an optional two-stop gradient, sizes in millimetres, error correction L to H, an optional centre image, an optional caption, PNG at 300 dpi with a real pHYs chunk and SVG.
The gate is the part worth writing down, because the gate was wrong four separate ways before it was right.
The Gate Is Easy; Trusting It Is the Work
The first version decoded the exported bitmap. That failed immediately, and instructively: a smooth or nearest-neighbour rescale blurs the one-pixel gaps between dot-style modules, so a code that prints perfectly was refused because of how the test resampled it. The gate has to re-ink the symbol from shapePath — the same vector geometry the exporters use — at a chosen pixel pitch, instead of scaling a picture of it.
The second version then did the obvious thing and probed at the print’s own resolution. At a 300 mm export that is 95 px per module and 3,500 px across, and at 150, 200 and 300 mm the same dot modules that decoded at every size below started failing above it. jsQR is a decoder written for photographs — a few hundred pixels across — and it has a working range. Probing at 95 px per module was testing the decoder’s comfort, not the design’s correctness.
The third version probed at a single low pitch, 8 px per module, which is what a 25 mm card gives. That broke the opposite way: a dot pattern that reads cleanly at 8 px per module can miss at 20, where jsQR’s 8 × 8 adaptive binarisation blocks and its module-centre sampling alias against the white gaps between circular dots. Refusing on one density means blaming a good design for a decoder blind spot.
The gate that shipped offers the symbol to the decoder at two pitches — the visitor’s own, capped at 24 px per module, and 8 px per module — and refuses only when both fail:
const nativePitch = Math.max(1, Math.floor(canvas.width / geo.total));
const pitches = [...new Set([
Math.min(nativePitch, PROBE_PITCH_MAX),
Math.min(nativePitch, PROBE_PITCH_MIN),
])];
let found: string | null = null;
let tried = 0;
for (const pitch of pitches) {
const side = geo.total * pitch;
if (side < 21) continue;
tried += 1;
probe.width = side;
probe.height = side;
pctx.imageSmoothingEnabled = false;
const scaled = centre ? rescaleCentre(centre, pitch / modulePx) : null;
paintSymbol(pctx, pitch, geo, gradient, scaled, inkDark, inkLight);
const pixels = pctx.getImageData(0, 0, side, side);
const hit = decode(pixels.data, side, side, { inversionAttempts: 'dontInvert' });
if (!hit) continue;
found = hit.data;
if (verifyDecode(expected, found) === 'ok') return 'ok';
}
if (tried === 0) return 'empty';
return found === null ? 'mismatch' : verifyDecode(expected, found);
One more exclusion belongs in this section: the caption band is not drawn into the probe. It is type under the code, not part of it, and at 80 mm and above its letterforms gave jsQR enough false finder candidates that a round-eyed design which decoded at 50 mm failed at 80 mm. A gate that fails on the caption is measuring the wrong object.
Four Blind Spots of a Clean Bitmap
With the gate honest, the tool still shipped codes that would fail in the physical world, because a clean bitmap at 8 px per module has a very specific set of things it cannot see. Each of the four below is now a rule with a measured number behind it.
1. The module floor. A 61-module payload — a vCard with a phone number and an address — at 20 mm gives 69 modules including the fixed four-module quiet zone each side: 0.29 mm per module on paper. The gate re-inks that same symbol at 8 px per module, decodes it, and unlocks the download, and the resulting sticker is unreadable on a laminated table tent. Ink spread, toner scatter and macro focus all live below the line the decoder never crosses. pitchCheck now refuses a print finer than 0.40 mm per module, and 0.50 mm for dots and soft corners, which lose ink at every gap, quoting the millimetres it measured rather than the limit it applied.
2. The centre image is an area problem, not a side problem. Level H recovers roughly 30% of codewords, and that budget is not only for the logo — it is what lets the code survive a thumbprint, glare, a crease and a phone held at an angle. A 30% image on a 29-module symbol looks conservative until the two-module white knockout pad is counted: 43.8% of the side, 19% of the area, deleted from a symbol whose read-back margin was measured on a clean bitmap. The cap is now 15% of the area, pad included (CENTRE_MAX_AREA), which means the same 30% slider is allowed on a dense vCard and refused on a short URL. That is the physics rather than a taste.
3. Red ink that a till scanner sees as paper. WCAG relative luminance weights green at 0.7152 and blue at 0.0722, so maroon #800000 on white scores 10.9:1 and sails through the 4.5:1 guard. On the raw 8-bit red channel — which is how the guard computes it — it scores 1.9:1, and a 660 nm red-LED scanner, the kind still bolted to a shop counter, is effectively colour-blind in exactly that band. Phones read red ink without trouble, so this is a warning and never a refusal: the file stays downloadable, the sentence names the ratio, and the choice belongs to whoever is printing.
4. Millimetre contracts: whole pixels, a caption band, and the pHYs chunk. At 300 dpi a module is an integer number of pixels, and on a 29-module symbol — 37 with the four-module quiet zone on each side — the planner rounds up, not down: ceil(box / (modules + 2 × quiet)). Flooring would print the 25 mm option at 21.9 mm, under the very floor the page warns about; ceiling can only make the code larger than asked, which is the safe direction for a camera. A requested 50 mm therefore lands at 50.1 mm, and for that symbol the export is 592 px across. A caption adds a band of 13% of the code width — five modules at that pitch, 6.77 mm — so the file is quoted as 50.1 × 56.9 mm: the code stays square, the paper does not. The pHYs chunk carries the same promise out of the browser. Without it a word processor falls back to 96 dpi and places those 592 px at 157 mm, three times the size the table tent asked for.
🔍 The two rules the decoder could not see: pitchCheck and the centre-image area cap (TypeScript, 30 lines)
export const MIN_MODULE_MM = 0.4;
export const MIN_MODULE_MM_DOTS = 0.5;
export interface PitchCheck {
ok: boolean;
mm: number;
floor: number;
}
/** Judge the module pitch of the print, not of the preview. */
export function pitchCheck(totalModules: number, actualMm: number, style: QrStyle): PitchCheck {
const floor = style === 'dots' || style === 'soft' ? MIN_MODULE_MM_DOTS : MIN_MODULE_MM;
const mm = totalModules > 0 ? actualMm / totalModules : 0;
return { ok: mm + 1e-9 >= floor, mm: Number(mm.toFixed(3)), floor };
}
export const CENTRE_MAX_RATIO = 0.3;
/** Share of the symbol's *area* the knockout may cover, pad included. */
export const CENTRE_MAX_AREA = 0.15;
export const CENTRE_PAD_MODULES = 2;
// inside planCentre()
const ratio = percent / 100;
const sidePx = Math.max(1, Math.round(input.codePx * ratio));
const padPx = Math.max(0, input.modulePx) * CENTRE_PAD_MODULES;
if (ratio > CENTRE_MAX_RATIO + 1e-9) problems.push('too-large');
// The pad is not decoration: it is four more modules of code that no longer exist.
const knockoutSide = sidePx + padPx * 2;
const occupied = input.codePx > 0 ? (knockoutSide / input.codePx) ** 2 : 1;
if (occupied > CENTRE_MAX_AREA + 1e-9) problems.push('too-much-area');
Every one of those rules runs on the page that generates the file: the QR Code Generator on tools.hoelee.com refuses an unscannable pitch or an oversized centre knockout before anything leaves the browser, so a print run does not depend on guesswork at the press. The four failures, side by side:
| Failure in the physical world | What a browser check sees | Gate rule |
|---|---|---|
| 61-module vCard printed at 20 mm | read-back at 8 px/module passes | refuse below 0.40 mm per module (0.50 mm for dots) |
| 29-module symbol, 30% centre image | clean-bitmap level-H decode passes | refuse above 15% of the area, pad included |
Maroon #800000 on white | WCAG 10.9:1, clears the 4.5:1 floor | red channel 1.9:1 → warn, never refuse |
300 dpi PNG without pHYs | displays correctly in the browser | write the chunk, quote 50.1 × 56.9 mm |
Proving the Gate Closes
A gate nobody has watched close is not a gate. The engine tests prove the arithmetic; a Playwright/CDP probe proves the page, and it deliberately does not trust the page’s own verdict. It finds the code’s black bounding box, verifies the timing row and column — a scaled, stretched, cropped or mistranslated drawing fails there even when jsQR still guesses a payload — and decodes the canvas with its own fresh import of the site’s lazy jsQR chunk, from pixels it read itself. A symbol only its author can read fails here.
The closure test is a seam built for exactly this: with data-simulate-mismatch="1" the widget’s read-back is fed a wrong string, and the probe asserts the download disappears. The gate has to withhold the file, not merely say it would.
That probe found three things the happy path could not:
- A centre image refused at load — 900 px against a 600 px cap — fell back to a code without the image and still offered the download. The silent drop the payload rules forbid. A refused file now withholds the export until it is cleared or replaced.
- The vCard’s CRLF cannot be seen in a textarea, because browsers normalise the value to LF on read. The probe folds newlines for the box and proves CRLF from the decoded canvas instead.
- A rebuild mid-run (
astro buildreplacingdist/whileastro previewserves it) turned a check red and then crashed the run on a missing geometry. Do not rebuild while a probe is running, and a probe should report a missing page as a failure rather than a traceback.
The check that was flattering the layout. The image tools on the same site keep the stage beside the form, so their contract is “the download is in the first screen”. This tool puts the code under a six-type form, and the first version of the probe asserted the same rule by calling scrollIntoView on the download block before measuring it — which measures “fits in a viewport once already scrolled there”, not “is on the first screen”. The honest property is that the buttons sit one glance under the code, measured in page coordinates so scrolling cannot help: at 390 px the block is 66 px below the code and 48 px tall, with 0 px of sideways overflow; at 1440 px the layout is two 518 px columns with the code at x = 719. A gate that scrolls the thing it is measuring into view is not a gate.
🔍 The probe's own decoder: independent of the widget's read-back (Python + injected JS, 24 lines)
# The probe's own decoder: the page's own lazy jsQR chunk, imported fresh. The canvas is drawn
# from the page's pixels at their native resolution — nothing resampled, nothing smoothed — and
# only the symbol square is read, because the caption band below it is type, not code.
DECODE_JS = """(async () => {
try {
const src = document.querySelector('[data-qr]');
if (!src || !src.width) return { found: null, note: 'no canvas' };
const w = src.width, h = src.width;
const c = document.createElement('canvas');
c.width = w; c.height = h;
const ctx = c.getContext('2d', { willReadFrequently: true });
ctx.imageSmoothingEnabled = false;
ctx.drawImage(src, 0, 0, w, h, 0, 0, w, h);
const img = ctx.getImageData(0, 0, w, h);
const chunk = performance.getEntriesByType('resource').map(e => e.name).find(n => /jsQR/i.test(n));
if (!chunk) return { found: null, note: 'no jsqr chunk' };
const mod = await import(chunk);
const fn = mod.default;
const hit = fn(img.data, w, h);
return { found: hit ? hit.data : null, size: [w, h] };
} catch (e) {
return { found: null, note: 'decode threw: ' + String(e) };
}
})()"""
A Phone Parser Paid for by a Page That Only Draws
The last failure in this round had nothing to do with QR codes and everything to do with how budgets fail. The three QR routes were the heaviest on the site — 78.7 to 79.6 KB against an 80 KB budget — and adding four sentences of new warning copy pushed them to 80.1–81.4 KB and failed npm run verify. Copy did not cost 2 KB.
The cause was the import graph. The QR generator’s engine imported its drawing helpers from the WhatsApp link builder’s engine, and that module pulls in libphonenumber-js at module scope: 28.7 KB of phone parsing, paid for by a page that only draws a code. The drawing half moved into whatsapp-link-builder/qr-core.ts, re-exported from engine.ts so every existing import kept working, and the QR tool imports qr-core directly. The three routes dropped to roughly 53 KB, and the heaviest route on the site is now the WhatsApp builder at 75.7 KB.
The transferable part: a bundle budget with 1.3 KB of headroom is not a budget, it is a countdown. It will fail on a text edit, and the diff will point at the text. The import graph has to be read before the sentence is blamed.
The Result
- 238 + 954 tests pass, 67 of them in the QR engine (10 added this round).
- 157 pages build,
astro checkreports 0 errors, bundle budget green. probe_qr_coderuns 300 checks green on the built site and again on the live site.probe_a11ycovers 234 checks, including the three QR locales.probe_whatsapp_linkis unchanged after the module split, which is the check that proves the refactor moved code without moving behaviour.- The heaviest QR route is now ~53 KB, down from 80.1–81.4 KB, against an 80 KB budget.
What I Would Build Again
The gate-earns-its-keep part of this was not jsQR. It was accepting that a decoder answers a narrower question than the one that matters. jsQR can tell me the symbol is internally consistent — right modules, right payload, no shear, no mistranslation. It cannot tell me whether a printer will place those modules far enough apart to survive ink, whether a logo’s knockout leaves enough error-correction budget for a thumbprint, or whether the ink absorbs light at the wavelength of the scanner on the counter.
So the rules that made this usable are all floors and budgets measured on paper: 0.40 mm per module, 15% of the area, four modules of quiet zone that are not a control, red-channel contrast as a warning rather than a wall. Every refusal quotes the number it measured — “0.29 mm per module” rather than “too small” — because a limit stated as a limit teaches nothing, and the person holding the file needs to know how far off the print is.
The probe’s lesson is the one I keep re-learning in other shapes: a verification that can be satisfied by the code doing the verifying is not a verification. Feed the gate a wrong string and watch the download vanish. Measure the layout the way the reader gets it, not the way the assertion prefers to arrange it first.
Dealing with flaky containers, cloud cost bloat, or unexplained outages?
Real production reliability comes from understanding the kernel and the protocol layers, not just restarting containers. I manage 162 containers across 3 hosts running 24/7 client workloads.