Building a Pure-TypeScript ISO/IEC 18004 QR Code Generator with Outlined SVG and Print-Ready CMYK EPS

2026-12-03来源 dev.toEnglish

Most "free" QR code websites follow the same bait-and-switch pattern: they generate a dynamic redirect URL pointing to their own tracking domain, let you print 5,000 business cards or product labels, and then deactivate the QR code 14 days later unless you start paying $15 to $49 per month.

Even the genuinely free generators almost always export low-resolution PNGs — or SVGs composed of 1,500 individual <rect> elements that render hairline anti-aliasing seams between adjacent black modules in PDF viewers, Adobe Illustrator, and commercial print RIPs.

For LogoNib's free Static Vector QR Code Generator, we built a zero-dependency ISO/IEC 18004 encoder directly in TypeScript (src/lib/logo/qr.ts) that runs 100% client-side in the browser and exports:

  1. Outlined <path>-only SVG with horizontally merged dark runs (zero hairline seams, zero fonts, zero external assets).
  2. Print-ready CMYK PostScript EPS (%!PS-Adobe-3.0 EPSF-3.0) via our browser-native SVG-to-EPS encoder.
  3. 2048×2048 PNG with optional center logo compositing inside an automatically calculated ECC Level H safe window.

Here is how the math, geometry, and security sanitization work under the hood.

1. Deterministic ISO/IEC 18004 Encoding in GF(256)

A QR code is a Reed-Solomon error-corrected bit matrix operating over the finite field $\text{GF}(2^8)$ with primitive polynomial $x^8 + x^4 + x^3 + x^2 + 1$ (0x11D).

Instead of pulling in an opaque WASM binary or third-party server API, our encoder handles every stage deterministically in ~800 lines of TypeScript:

  • Version selection (Versions 1–10): UTF-8 encodes the payload (URL, vCard 3.0, WIFI:, mailto:, or tel:) in Byte Mode (0100), picks the smallest ISO/IEC 18004 Table 9 version that fits the payload at the selected Error Correction Level (L, M, Q, or H), pads the data stream with alternating 0xEC / 0x11 bytes, and splits codewords across Group 1 and Group 2 blocks.
  • Reed-Solomon generator polynomials: Precomputes GF_EXP and GF_LOG lookup tables in GF(256) to divide each data block by the exact generator polynomial for that version's ecPerBlock count, then interleaves data and EC codewords per spec.
  • Function patterns & 8-mask penalty scoring: Places finder patterns, separators, timing tracks, alignment patterns, dark module, and BCH-encoded format/version information bits — then evaluates all 8 ISO/IEC 18004 data masks against the 4 standard penalty rules (consecutive runs, 2×2 blocks, finder-like 1:1:3:1:1 patterns, and dark/light balance) to pick the cleanest, easiest-to-scan matrix.

2. Center Logo Cutout Geometry & Automatic ECC Level H Lock

Placing a brand icon in the center of a QR code is the fastest way to break scan reliability if done blindly. At ECC Level L (7% recovery), even a small badge can push damaged codewords over the recovery threshold.

In generateQrMatrix(payload, { centerBadge: true }), enabling a center logo automatically locks Error Correction to Level H (30% codeword recovery) and computes a conservative centered square window via computeSafeCenterWindow(size):

  • The cutout width is bounded so its area stays strictly $\le 20\%$ of the QR matrix (typically ~14–18% depending on QR version), centered on the matrix and clear of all three finder patterns and timing tracks.
  • For Version 6 (41×41 modules, encoding a full HTTPS URL), the safe cutout is a 17×17 module window (17.2% of matrix area), giving comfortable white margin around a centered mark while keeping Level H recovery headroom intact.

3. Eliminating Hairline Seams: Horizontal Run-Merged <path> SVG & CMYK EPS

Naive QR SVG generators output one <rect> per dark module. On non-integer DPR displays, PDF viewers, and vector cutters, adjacent rectangles create faint white sub-pixel lines between squares.

Our renderQrSvg() walks each row of the boolean matrix, merges contiguous dark modules into single horizontal runs, and emits one unified <path d="..." fill="..." /> string:

  • Fewer DOM/SVG nodes and smaller file sizes.
  • Zero sub-pixel seams when zoomed to 1,000% or printed on signage.
  • Feeds directly into our pure-TypeScript SVG to EPS converter (convertSvgToEps), converting #RRGGBB foreground and background ink into exact device CMYK (setcmykcolor) PostScript vectors for print shops that still request .eps artwork.

We also run a live contrast audit (auditQrContrast) checking WCAG relative luminance between foreground and background ink, flagging low-contrast palettes (< 4.5:1) and inverted dark-background codes that trip up older phone camera scanners.

4. Safe Client-Side SVG Logo Uploads (Zero Same-Origin XSS)

Allowing users to upload their own .svg logo to overlay in the center of a QR code introduces a classic browser security risk: loading an untrusted .svg file into a same-origin image/svg+xml Blob URL or {@html} can execute embedded scripts.

To eliminate that class of vulnerability completely:

  1. Any uploaded .svg first passes through our preflight parser and strict sanitizer (auditSvgPreflight + optimizeSvg), stripping <script>, event handlers, foreign objects, and dangerous href/style payloads.
  2. We rasterize the sanitized SVG offscreen into a pure image/png Blob before drawing it onto the QR preview canvas — never rendering uploaded SVG markup directly in the DOM.
  3. Downloadable .svg files are constructed with MIME type application/octet-stream so browsers always download the vector source cleanly rather than executing it in a tab.

Try It Free (Plus Companion Print Tools)

Everything runs locally in your browser with zero login, zero watermark, and zero expiring redirect URLs:

And if you are launching a new business and need an original outlined vector logo (SVG, CMYK EPS, 300-DPI Print PDF, 4K PNG, ICO) with full commercial ownership for a single one-time payment ($29, $49, or $89 — no recurring subscription), you can try six custom vector concepts for your brand free in LogoNib Studio.

原文:https://www.a8q9.cn/en/article/building-a-pure-typescript-iso-iec-18004-qr-code-generator-with-outlined-svg-and-378341.html

相关文章