# Dynamsoft Codepool — Article Prose Corpus > The prose of every published Dynamsoft Codepool tutorial: barcode > scanning, MRZ scanning, document capture, document viewing, OCR and Web TWAIN > integrations, with sample code on GitHub. > > This is the full-text companion to /codepool/llms.txt, which is the index of > the same articles with one-line summaries. If you only need to decide which > articles to read, fetch llms.txt — it is far smaller. If you are quoting, > summarising or extracting from Codepool content, this file has the material. > > Code blocks are omitted; inline API names and section headings are retained. > Use each article's canonical URL below for complete code, images and links. > Unpublished drafts are not present. ## Category: Barcode ### GS1 2D Barcodes at Retail POS: A Developer's 2027 Readiness Checklist URL: https://www.dynamsoft.com/codepool/gs1-2d-barcode-pos-readiness-2027.html Summary: A developer's checklist for the GS1 2D transition at retail POS: which symbologies to accept, how to split the element string by the AI table, which GTIN to emit, how to stop a dual-symbol pack from ringing up twice, how to run the acceptance matrix, and a playable Canvas checkout example with source and tests. Author: Xiao Ling Published: 2026-11-02 (updated 2026-11-04) Topics: GS1, GS1 AI, GS1 Digital Link, DataMatrix, Retail, POSBy the end of 2027, GS1’s industry goal is for retail POS systems to read both today’s 1D barcodes and GS1-compliant 2D symbols carrying a GTIN, lot or expiry date — and resolve either carrier to one product identity. It is a capability goal, not a legal mandate, and EAN/UPC does not disappear. The failure this exposes is easiest to see at the till. A shampoo bottle carries a GS1 DataMatrix with batch and expiry, plus the EAN-13 printed on its old label artwork. The scanner reads both, and the checkout rings up two bottles. This is a data-model failure: the POS has treated “symbols decoded” as “items purchased”. For an integrator, readiness comes down to five decisions: which symbologies to accept, how to split the payload by the application-identifier table, which GTIN representation to emit, how to commit one cart line per package presentation, and which legacy behaviour must not regress. Two companion tutorials cover the mechanics: scan and parse GS1 barcodes with application identifiers builds the AI table and the decoder call, and generate GS1 barcodes in JavaScript produces the dual-marked labels this checklist assumes. ## Key Takeaways - The symbology is not the payload format. A Data Matrix and a GS1 DataMatrix are the same symbology with different content; only the presence of FNC1 in the first position (and the AIs that follow) makes it GS1. - Split by the AI table, not by punctuation. Fixed-length data is consumed by length, variable-length data runs to the next FNC1 byte or the end of the string. The table is prefix-free, which is what makes the split unambiguous. - A decoder that drops FNC1 turns a batch number into a plausible but wrong value. AI 10 allows 20 characters; a 21-character reading is provably wrong, and the right response is to reject the scan rather than to guess. - Emit GTIN-14, always. AI 01 already gives 14 digits; a legacy EAN-13 is the same product with a leading zero. Never renumber a GTIN when you reprint a pack. - De-duplicate a presentation, not a basket. Two symbols on one pack are one line; two identical bottles scanned one after the other are two lines. - A GS1 Digital Link is not a replacement for the element string. It is the same data written as a URL, and a POS must be able to accept it without a network round trip. ## Try the checkout rule in a browser In the dual-marked level, the checkout groups both carrier reads before committing one $2.50 cart line. The companion example is a single-canvas checkout game. It renders the symbols, groups the carrier reads by package presentation and shows the POS rule behind every cart change: The five scenarios run in the browser; the simulated part needs no camera or SDK license. Scan one pack with both EAN-13 and QR, scan two identical packs in separate presentations, then create a two-GTIN conflict in the sandbox. The cart decision and the rule that produced it appear beside the package. The simulation is kept separate from the SDK image decode, so an SDK failure cannot become a fabricated success. The lab uses EAN-13 and a GS1 Digital Link QR. It is the visual counterpart to Decision 4 below, not a substitute for the DataMatrix parser cases in the acceptance matrix. Run the hosted checkout lab ## What GS1 actually committed to The 2027 date is an industry POS capability goal, not a mandate covering every barcode. GS1’s retail programme — for years called Sunrise 2027, now usually “Ambition 2027” — asks that a checkout be able to read a 1D symbol and a GS1-compliant 2D symbol, and get the same product identity from either. GS1’s own background note states what the date is for and what it is not ( GS1: why 2027? ). Three consequences follow, and each one removes work rather than adding it: - This is not a mandate. No regulator is going to fine a retailer for scanning an EAN-13 in 2028. The pressure is commercial: brand owners want lot and expiry data at the till, and the POS that cannot read it is the one that blocks the rollout. - 1D stays. GS1 DataBar for variable-measure items and EAN/UPC for everything already printed are not going away. A “2D migration” that stops reading 1D symbols is a regression, not a migration. - One pack can carry both, and the POS must commit once. The GS1 implementation guideline for 2D at retail POS ( release 1.1.0 ) addresses this directly: when several on-pack symbols identify the same trade item, the system processes one GTIN and issues one POS acknowledgement — one cart line or one beep, not one per symbol. That is the de-duplication requirement many integrations miss. ## Decision 1 — Which symbologies must a POS accept? Most of the formats are already in a retail scanner’s format list; the trap is assuming that enabling a symbology is the same as accepting GS1 data. Format | What it carries | Why the POS needs it | EAN-13, UPC-A, UPC-E | A bare GTIN, no AIs | The installed base. Every existing pack. | GS1 DataBar (Omnidirectional, Expanded, Limited, Stacked) | A bare GTIN usually; Expanded can carry weight and price | Variable-measure produce and meat; small packs where an EAN-13 will not fit | ITF-14 | A bare GTIN-14 | Corrugated cartons, case-level scanning | GS1-128 | AI element string | Logistics and case labels | GS1 DataMatrix | AI element string | The main 2D carrier at item level: GTIN + expiry + batch + serial | GS1 QR Code | AI element string, often as a GS1 Digital Link URI | Consumer-facing packs; the same symbol serves the customer’s phone and the till | A distinction that frequently causes confusion is between the plain-symbology rows and the two GS1 2D rows. A plain Data Matrix and a GS1 DataMatrix are the same symbology ; the difference is encoding. A GS1 symbol starts with FNC1 in the first position, which is what tells a conformant decoder “this is an element string, not arbitrary data”. Decoders that expose the AIM symbology identifier report it as ]d2 for GS1 DataMatrix, ]Q3 for GS1 QR Code, ]C1 for GS1-128 and ]e0 for GS1 DataBar; the plain forms report ]d1 , ]Q1 and so on. The check in the pipeline is therefore not “did I get a DataMatrix?” but: A GS1 QR Code that carries a Digital Link URI ( https://id.gs1.org/01/… ) is a special case worth handling explicitly — see Parsing a GS1 Digital Link without breaking checkout . The three carriers a checkout actually meets return three different payload shapes, and the POS normalizes all of them to GTIN-14: Carrier | Raw payload | Where the GTIN sits | Can carry lot / expiry / serial | EAN-13 | 950600137562 | The whole payload | No | GS1 DataMatrix | 010095060013756210LOT-32763 | After AI 01 | Yes, if printed | GS1 Digital Link QR | https://id.gs1.org/01/00950600137562/10/LOT-32763?17=280813 | Path segment after 01 | Yes, if present | Only the two GS1 2D carriers can carry the fields that justify the migration. A GTIN-only DataMatrix is not a defective label; it identifies the product and stops there, and the POS should record “no lot, no expiry” rather than fill them from the SKU row. The QR row is also the one most often mistaken for a network feature: the identifiers are in the URL, so the parser needs no resolver and no round trip. ## Decision 2 — How do you split the payload? A GS1 element string is a concatenation: 01 + 14 digits, then 17 + 6 digits, then 10 + up to 20 characters, and so on. There is no delimiter between fields. The only things that make the split possible are the AI table and the FNC1 byte. - Fixed-length AIs are consumed by length. 01 always takes 14 characters, 17 always takes 6. No separator follows them. - Variable-length AIs run to the next FNC1 ( 0x1D ) or to the end of the payload. AI 10 is the usual suspect. - The table is prefix-free. No two-digit AI is the prefix of a three- or four-digit one, so “longest match wins” is safe. That property is why a length-driven split works at all. Here is what the GS1 barcode scanner demo returns for a Sunrise 2027 pack — a GS1 DataMatrix printed beside a legacy EAN-13, decoded and parsed by the page’s own AI table: The | is the FNC1 separator, normalised. Now remove it — which is what a decoder that returns a flat string does — and the same payload parses into something that looks entirely reasonable and is wrong: LOT-3276321SN1 is not a batch number. It is the batch number with the serial number glued onto it, and the only reason anyone can prove that is the length rule: AI 10 allows at most 20 characters, and this reading used 21. Two behaviours are defensible here, and they serve different purposes. The demo re-splits at the longest head whose remainder still parses, and reports that it did — which is right for a diagnostic tool, because you want to see the plausible-but-wrong answer next to the rule that condemns it. A POS integration should fail closed : no GTIN, no line, ask the cashier to rescan. A wrong batch number in a recall system is worse than a scan that needs repeating. ## Decision 3 — Which GTIN do you emit? One value, one representation: GTIN-14 in the product table . AI 01 already carries 14 digits, so the 2D path needs no conversion. Common conversion bugs occur on the legacy path: - An EAN-13 is a GTIN-14 whose packaging indicator is 0 . 950600137562 and 00950600137562 are the same product. Zero-pad on the way in, and never strip the zero on the way out. - UPC-E must be expanded to UPC-A before zero-padding; the compressed form is an encoding, not an identifier. - A GTIN-14 with a non-zero packaging indicator ( 1…8 ) is a case or a multipack, not the unit. Do not collapse it into the unit GTIN. - Never renumber a GTIN because you moved to 2D. The GTIN is printed on packaging that was manufactured months ago and is sitting in a warehouse. GS1’s guidance is to keep the existing GTIN; a new symbol with a new number is a different product to every system downstream. ## Decision 4 — How do you avoid double counting? The rule that satisfies the GS1 guideline is small, but its scope matters: an implementation that keys on GTIN alone breaks a routine purchase — buying two of the same item. De-duplicate reads that belong to one presentation of goods. Never de-duplicate across a basket or a transaction. A customer lifts a bottle, the scanner reads the DataMatrix and the EAN-13 in the same presentation, and that is one line. The cashier scans a second identical bottle, which is a separate presentation, and that is a second line. If you key on GTIN alone for the whole transaction, the second bottle vanishes from the receipt; if you key on the decoded symbol, the first bottle appears twice. Run against the two reads from the pack above, that returns a single line with two sources: The sources array is worth keeping. When a store reports “the scanner double-scanned”, the array tells you whether the POS was handed two symbols or one symbol twice — two different bugs with two different fixes. That function is the happy path. A production implementation has to name the outcomes, because each one has a different till behaviour: Outcome | Trigger | Till behaviour | added | One GTIN in the presentation, product known | One line, one beep | ignored | The same presentation is committed twice | Nothing; the pack was already counted | needs_review | Two different GTINs, or an unknown GTIN | Block the line, call an attendant | not_added | No valid GTIN, or a failed check digit | Re-scan prompt, no line | Two of those deserve their own rule. Conflicting GTINs are not a tie-break : if the EAN-13 and the 2D symbol disagree, the pack has a labelling defect, and picking the 2D symbol because it is newer hides it. An unknown GTIN is not a new product : it is a catalog gap, and inventing a line for it corrupts the basket. The five scenarios worth encoding as fixtures: Scenario | Carriers in one presentation | Presentations | Expected | Traditional | EAN-13 | 1 | added , quantity 1 | Two-dimensional | GS1 Digital Link QR | 1 | added , quantity 1 | Dual-marked | EAN-13 + Digital Link QR, same GTIN | 1 | added , quantity 1 | Two products | EAN-13 + Digital Link QR, same GTIN | 2 | added , quantity 2 | Mismatch | EAN-13 GTIN A + QR GTIN B | 1 | needs_review , quantity 0 | The presentation boundary comes from the application, not from a timer. A 500 ms window merges two packs that pass close together and splits one pack that is held still; an explicit presentationId does neither. Camera frames are the other half of the problem: ten reads of one symbol inside a presentation are one observation set, while a second identical bottle needs a second presentation. A barcode cannot count physical units — if two identical bottles are presented together, the UI has to ask. ## Decision 5 — What legacy behaviour must not regress? A 2D rollout is usually a firmware change, a middleware upgrade and a POS release delivered together, which is when quiet regressions tend to appear. A practical regression checklist: Behaviour | Why it breaks, and what to test | EAN-13 / UPC-A read at full trigger speed | A new format list that enables 2D at the cost of 1D scan rate is a net loss. Time 100 scans before and after. | Check digit validated on every path | Some 2D middleware forgets it because the AI parser “already checked the GTIN”. It did not check the SSCC or the GLN. | UPC-E expanded correctly | A new parser that assumes 13 digits turns a valid UPC-E into a wrong GTIN-14 silently. | Variable-measure price embedded ( 02 / 37 on DataBar Expanded) | The weight and price AIs must still drive the line total, not just the GTIN. | Keyboard-wedge output unchanged | Handheld scanners in HID mode emit a keystroke stream; a middleware that now expects JSON breaks every legacy lane. | Manual keypad / PLU path untouched | The fallback when a label is damaged. Nobody tests it until the first damaged label. | ## Parsing a GS1 Digital Link without breaking checkout A GS1 Digital Link is the same element data written as a URL: https://id.gs1.org/01//10//21/ . The primary key is always /01/ ; other AIs appear either as path segments or as query parameters ( ?17=280813 ), and both forms exist on real packaging — the demo above emits the path form for AI 10 and 21 and the query form for 17 . Three rules keep it from becoming a checkout outage: - Accept it offline. The identifier is in the symbol; resolution is a separate, later step. A POS that fetches id.gs1.org before ringing up an item has put a network dependency in the payment path. - Do not confuse it with the element string. https://…/01/00950600137562 is not an AI element string and will not parse as one. Detect the URI form first, then read AIs out of it. - Resolution is not authentication. A resolvable link proves the link resolves. Signature verification and brand-owner attestation are separate mechanisms, and this article does not claim either. ## An acceptance matrix you can run in an afternoon The matrix below is the one this article was tested against. Every row is a payload, not a photograph, so it can be asserted exactly; the images that carry those payloads can be regenerated on demand. Download the acceptance matrix as CSV — 12 cases, expected GTIN, expected elements and the pass rule for each. in the payload column is the FNC1 byte, 0x1D . # | Case | Expected | What a PASS proves | A1 | GS1 DataMatrix, GTIN only | PASS, GTIN 00950600137562 , 1 element | The 2D path produces an identity at all | A2 | GTIN + expiry + batch + serial | PASS, 4 elements | FNC1 handling on a variable-length AI | A3 | A2 with FNC1 removed | REJECT | The parser fails closed instead of inventing a lot number | A4 | DataBar, bare GTIN, no AI | PASS + warning | AI 01 inference is disclosed, not silent | A5 | Legacy EAN-13 | PASS, same GTIN-14 | Zero-padding on the legacy path | A6 | A2 and A5 on one pack | PASS, one line | The GS1 guideline’s one-acknowledgement rule | A7 | GTIN + weight + price | PASS, 0.125 kg , 15.00 | Variable-measure AIs still drive the total | A8 | GTIN with a bad check digit | FAIL | Nobody rounds a check digit to make a sale | A9 | Plain Data Matrix, not GS1 | REJECT | A 2D code is not automatically a product | A10 | Variable AI last, no trailing FNC1 | PASS | End of payload terminates a variable AI | A11 | Expiry with day 00 | PASS, 2028-08-31 | The day- 00 rule is applied, not passed through | A12 | Digital Link URI in a GS1 QR Code | PASS, offline | URI form parsed without a network call | To build the images: open the GS1 barcode generator , choose the Retail 2D (Sunrise 2027) preset — it prints a GS1 DataMatrix and derives the EAN-13 from the same GTIN, which is exactly case A6 — and download the label PNG. For custom cases, type the AIs yourself. Then scan the PNG in the GS1 barcode scanner and compare against the matrix row. For volume rather than one pack at a time, the barcode scanner demo reads a whole dataset ZIP with ground truth and scores recall, precision, symbology agreement and box overlap — the same method behind the barcode benchmark index . A row that FAILs is information, not a verdict on a vendor. Cameras, print density and ambient light decide whether a symbol is readable at all; the matrix decides whether the software interprets what it read. ## Parsing reference implementation The JavaScript below was run against every case in the matrix before this article was published. It needs no SDK: it starts after the decoder has handed you a payload string, the layer integrations commonly misunderstand. JavaScript — parse, then de-duplicate: The JavaScript parser returns no GTIN at all when a payload is rejected, which is the point: the failure state has to be “no product”, not “probably this product”. ## What not to do - Do not strip leading zeros to “normalise” a GTIN-14 into a GTIN-13. You have just made the 2D path and the legacy path disagree about the same bottle. - Do not assume a 2D code is GS1. A QR code on a coupon, a Data Matrix on a tyre wall and a GS1 DataMatrix on a medicine box arrive as the same symbology to the decoder. - Do not trust a GTIN without the check digit. It is four lines of arithmetic and catches a common silent failure in the chain: a decoder that dropped a character. - Do not de-duplicate across the basket. Two identical items are not a duplicate. - Do not require network resolution at the till. See above. - Do not claim ISO verification because you ran a scanability check. A software preflight measures pixels; ISO/IEC verification is a calibrated process with a defined aperture, and the two are not interchangeable. ## Common Developer Questions ### Do I have to support both GS1 DataMatrix and GS1 QR Code? For item-level retail, GS1 DataMatrix is the workhorse and GS1 QR Code is often chosen when the same symbol has to serve a customer’s phone. A POS that accepts only one will encounter packs it cannot read. If you must sequence the work, do DataMatrix first and QR second — the parser is the same; the only new code is the Digital Link URI branch. ### What does “GS1-compliant 2D” mean, precisely? It means a 2D symbol whose payload is a GS1 element string — FNC1 in the first position, then AIs and their values per the General Specifications — or a GS1 Digital Link URI. It does not mean “any 2D symbol that happens to contain a GTIN-looking number”. ### My scanner returns the payload with (01) and brackets around every AI. What is that? That is the human readable interpretation, not the encoded data. (01)00950600137562 is what GS1 prints under the symbol; the encoded payload is 0100950600137562 . HRI is for humans and for logs — feeding it back into a parser that expects the raw form produces an immediate “no AI at offset 0” error, which is at least a loud failure. ### Where do lot and expiry come from if the symbol only carries a GTIN? They do not exist in that payload. GS1 DataBar and EAN-13 carry identity only; a GS1 DataMatrix or GS1 QR Code can also carry batch and expiry. A POS that stores those fields has to record which carrier supplied them; otherwise a later 1D scan can overwrite values supplied by an earlier 2D read. ### Is the 2027 date going to slip? That is a business question, not a technical one, and this article does not forecast it. The engineering argument for starting now does not depend on the date: a POS that de-duplicates a dual-symbol pack and validates a check digit correctly is a better POS in 2026 as well. ## Standards version, data rights, and what this article does not claim - Standards basis. GS1 2D Barcodes at Retail Point-of-Sale Implementation Guideline, release 1.1.0 ; GS1 retail solution provider 2D readiness ; GS1 background on the 2027 date . Accessed 23 October 2026. - Test data. Every payload in the matrix is synthetic. 00950600137562 is a generated GTIN, not a real product; no retailer, brand or document holder data is reproduced here. The labels used to produce the images were generated by the Codepool GS1 generator, so the fixtures can be regenerated by anyone. - Code status. The JavaScript parser was run against all 12 matrix cases on 23 October 2026. It implements the AI table for the AIs used here, not the complete GS1 table — extend FIXED and VARIABLE before production use, and keep the “unknown AI” path failing closed. - Not claimed. This article does not claim ISO/IEC barcode verification, GS1 certification of any implementation, or that any particular scanner hardware will read a given pack. Those are separate tests with separate evidence. ## Source Code The complete sample includes the Canvas checkout, the GTIN and Digital Link parser, five guided scenarios, synthetic fixtures and the tests that check each expected cart decision. Get the complete sample project source code on GitHub ### How Much Damage Can a PDF417 Barcode Take? A Visual Guide to PDF417 Error Correction Levels URL: https://www.dynamsoft.com/codepool/pdf417-error-correction-visualizer.html Summary: PDF417 error correction is a fixed codeword budget, not a percentage: level 0 buys 2 Reed-Solomon parity codewords and level 8 buys 512. Build, damage and decode PDF417 symbols in the browser with Dynamsoft Barcode Reader, and see where each level actually gives up. Author: Xiao Ling Published: 2026-10-22 (updated 2026-10-23) Topics: PDF417, Error Correction, Reed-Solomon, Barcode Reader, JavaScriptA PDF417 barcode on a driver’s license spends years in a wallet: folded, scuffed, printed on a card that gets wiped with a thumb every time someone checks an age. It still scans, because the symbol carries Reed-Solomon parity codewords that a reader can use to rebuild what the wear destroyed. So how much damage can a PDF417 barcode take? The honest answer is a number of codewords, not a percentage: level 0 spends 2 codewords on error correction, level 8 spends 512, and a single Reed-Solomon block repairs up to half of them when it has to find the errors itself — or all of them when it can tell which codewords are unreadable. Because the budget is a count and the symbol grows with the payload, the same level is 24% of a short symbol and 4% of a long one. This article makes that budget visible. We encode PDF417 symbols in the browser with an encoder that exposes the codeword behind every 17-module cell, damage them on purpose, and decode the results with Dynamsoft Barcode Reader — including the cases where the parity budget is untouched and the decode still fails. What you’ll learn: how a PDF417 symbol lays out its rows, codewords and row indicators; why its error correction levels are absolute counts rather than percentages; why guard patterns and row indicators fail outside the Reed-Solomon budget entirely; and what a seeded codeword sweep measures at levels 0, 2, 5 and 8 on the same payload. ## Key Takeaways - PDF417 levels are codeword counts. Level L carries 2^(L+1) parity codewords: 2 at level 0, 512 at level 8. A percentage is only a side effect of how big the symbol is — level 2 is 24% of the demo’s 33-codeword symbol and 4% of a 216-codeword symbol carrying 400 characters. - The repair budget has two bounds. A block of k parity codewords repairs ⌊k/2⌋ unknown errors, or up to k erasures — codewords the reader can tell are unreadable. A wiped cell is unreadable by construction, so in this demo a level-2 symbol with a budget of 4 decoded through 6 corrupted codewords and failed at 7. - Most of a high-level symbol is parity. At level 8 the demo’s 546-codeword symbol carries 512 parity codewords; only 34 carry data, padding and the length descriptor. That is why level 8 tolerates 214 wiped codewords — 39% of the symbol — before it breaks. - Three things protect a PDF417 row, and only one of them is parity. The start and stop patterns let a reader find the row, the left and right row indicators carry the row’s geometry twice, and the codewords carry Reed-Solomon parity. Wiping every row indicator on both sides produced 0 corrupted codewords and no decode ; inverting every guard pattern produced the same, in 180 ms. - A failed decode is not automatically “out of budget”. The demo reports corrupted codewords, damaged indicators and damaged guards separately, and says “exact cause not determined” when the budget was not exceeded — because a reader can lose a row before error correction is ever reached. ## Common Developer Questions ### What are the PDF417 error correction levels 0 to 8? The nine PDF417 levels set how many Reed-Solomon parity codewords a symbol carries: level L carries 2^(L+1) , from 2 at level 0 to 512 at level 8. Unlike QR Code levels, which are defined as a percentage of the symbol, a PDF417 level is a fixed count — so a large symbol at a low level spends almost nothing on redundancy, and a small symbol at a high level is mostly redundancy. The number of parity codewords also decides the repair budget: ⌊k/2⌋ unknown errors, or up to k erasures. ### How much damage can a PDF417 barcode take before it stops scanning? In this demo’s seeded sweep on a 35-character payload, decoding Dynamsoft Barcode Reader at default settings: a level-0 symbol (27 codewords, 2 parity) failed at the first corrupted codeword, level 2 (33 codewords, 8 parity) decoded through 6 corrupted codewords and failed at 7, level 5 (90 codewords, 64 parity) decoded through 34 and failed at 40, and level 8 (546 codewords, 512 parity) decoded through 214 and failed at 268. The limits are codeword counts, not percentages of the printed area, and they move with which codewords are hit. ### Why does a PDF417 barcode sometimes fail even though error correction should cover it? Because error correction only repairs codewords that a reader has already read as part of a row. If the start or stop patterns are gone, the row cannot be found; if both row indicators of a row are destroyed, the reader cannot tell which row it is looking at or how big the symbol is. Neither is protected by parity. In this demo, wiping the row indicators on both sides of every row left the corrupted-codeword count at 0 and the decode failed anyway. A reader can also lose a row to blur or low resolution long before the parity budget runs out. ### Is a PDF417 barcode with 512 error correction codewords as good as it sounds? It is as expensive as it sounds. Level 8 on a 35-character payload produces a 13-column by 42-row symbol in which 512 of 546 codewords are parity — about 94% of the ink is redundancy, and the symbol is roughly nine times the area of the level-2 version of the same payload. Level 8 is worth it for marks that will be abused, such as an ID card barcode read after years of handling; it is a poor default for a label printed on clean paper. ### Which PDF417 error correction level should I use? Pick the smallest level whose symbol still survives the damage you expect, because every step up spends codewords and area. At 35 characters, level 5 costs 90 codewords (64 of them parity) and level 8 costs 546 — nine times the printed area for eight times the repair budget. The demo makes the trade visible: switch levels, watch the parity share and the module width change, then run a sweep to see where each one actually breaks on the damage pattern you care about. If the symbol has to survive years in a wallet, buy the redundancy; if it is printed once on clean paper, level 2 or 3 is usually the better deal. ## Online Demo https://www.dynamsoft.com/codepool/demos/pdf417-error-correction-visualizer/ ## Demo Video: Damaging and Decoding PDF417 Symbols Live The video walks the core loop: step through levels 0, 3 and 8 to see the symbol change size, scratch a level-5 symbol, cover three rows until the corrupted count passes the budget, then run a seeded codeword sweep and read the pass/fail boundary off the log. ## Prerequisites - A modern browser. The PDF417 encoder runs entirely client side; decoding needs a secure context (HTTPS or localhost) for license activation. - A Dynamsoft Barcode Reader license for your own deployment. The hosted demo activates its Codepool license automatically. Get a 30-day free trial license for Dynamsoft Barcode Reader. ## PDF417 Anatomy: the Parts of a Stacked Symbol A PDF417 symbol is not a grid of codewords with a border painted around it. Each row is a complete, self-describing line: a start pattern, a row indicator, the codewords, a row indicator, a stop pattern. A scanner can lock onto any row and read it without its neighbours, which is exactly why the format tolerates a torn or obscured edge. Term | What it is | If it is damaged | Start pattern | 17 modules at the left of every row, in the pattern 8-1-1-1-1-1-1-3 | The row cannot be found; no parity applies | Stop pattern | 18 modules closing every row — one wider than the start pattern | Same: the row is not terminated where the reader expects | Left row indicator | One codeword carrying the row number, the row and column count and the level | The reader can use the right one instead | Right row indicator | The same geometry, repeated at the other end | The reader can use the left one instead | Length descriptor | The first codeword of the data region: how many data codewords follow | The reader cannot split data from parity | Data codewords | The payload, in text or byte compaction | Consumes the Reed-Solomon budget | Padding codewords | Value 900, filling the data region to its even size | Nothing: they are fill | Error correction codewords | 2^(L+1) Reed-Solomon parity codewords over GF(929) | Consumes the same budget as a data codeword | Quiet zone | Two modules of white on all four sides | The reader may not find the symbol’s edges | Row height | Each row drawn at least three modules high | Below that, rows blur together when printed small | The structure view in the demo paints that map onto the live symbol: white cells are payload, grey cells are padding, orange cells are parity, and the blue-grey strips at both ends are the indicators and guard patterns. Clicking a cell reports its codeword index and value. ## How a PDF417 Symbol Spends Its Redundancy Three separate mechanisms keep a PDF417 symbol readable, and they fail in different ways. The guard patterns are the start and stop patterns of every row. They are not codewords, they carry no data, and they are not protected by anything. A PDF417 reader finds rows by looking for that 8-1-1-1-1-1-1-3 run and its 18-module counterpart, and if they are gone the row is not there as far as the reader is concerned. The row indicators are codewords, but not Reed-Solomon codewords. Each one encodes the row number, the number of rows and columns in the symbol, and the error correction level — the geometry a reader needs to reconstruct the grid. Every row carries that information twice, at both ends, which is why wiping all the left indicators in a 42-row symbol still decodes: the reader reads the right ones instead. Wipe both and it has nothing to rebuild the grid from. The Reed-Solomon block is the only part that repairs damage. PDF417 uses a single block over GF(929) — one block for the whole symbol, unlike QR Code’s interleaved blocks — and the parity codewords are the last 2^(L+1) codewords in the sequence. They are placed after the data in row-major order, so at a high level the bottom of the symbol is almost entirely parity. That last point is what makes the parity share move. The level fixes the count , not the fraction: Payload | Level | Codewords | Parity | Share | Repair budget | 35-character URL | 2 | 33 | 8 | 24% | 4 | 35-character URL | 8 | 546 | 512 | 94% | 256 | 400 characters | 2 | 216 | 8 | 4% | 4 | The demo’s level bar chart recomputes all nine rows for whatever payload is in the box, so the trade-off is a number rather than a rule of thumb: level 8 on a short payload is a wall of parity, and level 2 on a long one is a rounding error. ## Step 1: Encode with the Codeword Map Exposed The demo ships a dependency-free PDF417 encoder so the page can name every part of the symbol it draws. Its output is bit-identical to a reference BWIPP encoder for payloads inside the PDF417 text set — same codewords, same row indicators, same module matrix — which is how the encoder was checked. Each cells entry is one 17-module codeword, and its role is what makes the budget meter possible: a cell is either payload, padding, the length descriptor, or parity. The index tells you where it sits in the codeword sequence, so the parity cells are exactly the ones at index dataCodewords and above. The encoder also emits the row indicators with the formulas from ISO/IEC 15438: for row i , the cluster is i mod 3 , and 30 * floor(i/3) is split across the row number, the column count and the level depending on the cluster. That is why a reader can reconstruct the grid from a single row. ## Step 2: Turn Damage into a Codeword Count When you drag across the symbol, the demo wipes whole codeword cells: all 17 modules of a cell go dark, which turns a valid pattern into a solid bar that no decoder can read as the value it used to hold. Counting the damage is then a diff against the clean matrix, not an estimate: Two consequences follow from that model, and the demo’s meter shows both. Corrupting a parity codeword costs exactly as much as corrupting a data codeword. Reed-Solomon does not know which is which until it tries to decode; every corrupted codeword in the block is one error, wherever it sits. The budget has two bounds, and a wiped cell is the cheap kind. A block of k parity codewords repairs ⌊k/2⌋ errors it has to locate, or up to k erasures — codewords it knows are unreadable. A solid black cell is unreadable by construction, so the reader can often spend one parity codeword on it instead of two. The meter draws both marks: a solid tick at ⌊k/2⌋ and a dashed one at k . ## Step 3: Decode the Damaged Render The damaged render is decoded the way a camera would see it: the clean module grid plus the damage, drawn onto one canvas and passed to Dynamsoft Barcode Reader as a raw frame. Canvas ImageData is RGBA in byte order, which is exactly what the SDK calls IPF_ABGR_8888 : A successful read returns more than text. item.details is a PDF417Details object, and for the demo’s default symbol it reports 11 rows, 3 columns, error correction level 2, both row indicators present and 33 codewords read — the same geometry the encoder produced. That cross-check is worth having: it proves the encoder’s layout matches what a real decoder expects, rather than only matching itself. The decoder runs on your device. The first decode downloads the WebAssembly engine (about 12–14 seconds on this connection, including license activation), and later decodes of a symbol this size settle around 20–60 ms — fast enough to decode automatically after every change. ## What the Sweep Shows: Level 0 to Level 8 The sweep corrupts codewords one at a time, in a seeded order, and decodes after each step. The x-axis is the budget’s own unit, so the failure point reads directly against ⌊k/2⌋ and k . Same payload, same reader, same seeds: Level | Symbol | Parity k | Error bound ⌊k/2⌋ | Erasure bound k | Decoded up to | First failure | 0 | 3 × 9 | 2 | 1 | 2 | 0 | 1 | 2 | 3 × 11 | 8 | 4 | 8 | 6 | 7 | 5 | 5 × 18 | 64 | 32 | 64 | 34 | 40 | 8 | 13 × 42 | 512 | 256 | 512 | 214 | 268 | Read the table from top to bottom and four things stand out. - Level 0 has no margin at all. Two parity codewords, a budget of one, and the very first corrupted codeword ended the decode. A level-0 PDF417 is a symbol that has decided not to be damaged. - The failure point sits between the two bounds, and it moves. Level 2 reached 6 of its 8 erasure-equivalent codewords, level 5 reached 34 against a 32-error bound, level 8 reached 214 against a 256-error bound. The reader is using erasure information when it can tell a codeword is gone, and falling back to error decoding when it cannot — how much of each depends on the damage pattern. - The percentages are misleading, the counts are not. Level 8’s 214 codewords are 39% of the symbol’s codewords and about 30% of its modules, while level 2’s 6 codewords are 18%. A single number like “PDF417 survives 30% damage” is an artefact of which symbol you printed. - The boundary is repeatable but not universal. Every run uses fixed seeds, so these rows reproduce exactly. They are still one reader at default settings on one payload; a different reader, a print-and-scan round trip or a different damage order can move the cliff by several codewords. ## Why a PDF417 Can Fail With Budget Left The most instructive result in the demo is the one where the budget meter stays at zero. Wipe every row indicator on both sides of every row — 36 indicator codewords of geometry at level 5 — and the corrupted-codeword count is 0 , because indicators are not part of the Reed-Solomon block. The decode fails in about 300 ms. Do the same to only the left side and it still decodes, because every row repeats its geometry at the right end; the reader simply reads the other copy. Invert every start and stop pattern instead, and the decode fails in under 200 ms with the budget still untouched. That is the boundary between correction and detection, and it is the reason the demo reports three numbers instead of one. Reed-Solomon repairs codewords. It cannot repair the row structure that tells a reader where those codewords are. When the budget is intact and the decode still fails, the page says so — “detection or sampling failed first, exact cause not determined” — rather than blaming error correction. ## Common Issues & Edge Cases - The corrupted count stays at 0 while the symbol gets visibly worse: that is the guard and indicator damage described above. The meter warns separately, because counting it as codeword damage would be wrong. - A decode succeeds past the ⌊k/2⌋ budget: expected. Wiped cells are erasures, and erasures cost half of what located errors cost. The dashed mark on the bar is the erasure bound, k . - A decode fails below the budget: also expected, for the reasons above, and for rows lost to blur, low contrast or resolution before any codeword is even read. - The first decode takes seconds, the rest take milliseconds: the reader downloads its WebAssembly engine on first use. Preload it on page load if your application decodes on a user action. - The symbol does not match the payload box: PDF417 has a hard capacity limit of 928 codewords, and at level 8 that leaves 415 for the payload. The page reports the overflow and keeps the previous symbol rather than drawing something that does not decode. - Digits cost more than they should: this encoder implements text and byte compaction, not numeric compaction. Ten digits ride the Mixed sub-mode at about 1.33 codewords per digit instead of 0.41, so digit-heavy payloads come out larger than a production encoder would make them. ## Real-World Constraints The numbers in this article are measurements from this demo: one payload, one encoder, Dynamsoft Barcode Reader at default settings, damage applied at the codeword level to a rendered image. That isolates the error correction mechanism and nothing else. A real PDF417 on a driver’s license also faces print gain, laminating, scratches that smear rather than erase, and a camera at an angle — none of which are codeword-aligned, and all of which can push the failure point in either direction. A printed symbol also has module widths in tenths of a millimetre; a 13-column level-8 symbol on a 5 cm card leaves modules that a phone camera may not resolve, which is a resolution failure, not an error correction one. Treat the sweep as a way to understand and compare the levels, not as a certified damage rating. If you need a print-quality verdict, that is a job for an ISO/IEC 15415 verifier, not a browser tool. ## Conclusion PDF417 error correction is a countable resource: 2^(L+1) parity codewords, one block, a budget of ⌊k/2⌋ unknown errors or k erasures. Because the level is a count rather than a percentage, the same setting can be 24% of a small symbol or 4% of a large one — and the interesting failures are not the ones where the budget runs out, but the ones where the guard patterns and row indicators are gone and the budget never gets used. Once you can see the codeword behind every cell, “how much damage can a PDF417 take” becomes an experiment instead of folklore: wipe cells, watch the count, and read the answer off a real decoder. The natural next step is the QR Error Correction Visualizer , which runs the same experiment on a QR Code where the parity budget is a percentage — the comparison makes the PDF417 design choice obvious. If you need to generate the symbols in the first place, the Driver’s License Generator builds a synthetic AAMVA PDF417 barcode, and the Barcode Structure Diagram annotates the regions of other symbologies the same way. ## Source Code Get the complete sample project source code on GitHub ### What Is an EMV QR Code? Build and Read a Payment QR in JavaScript URL: https://www.dynamsoft.com/codepool/emv-qr-code-generator-scanner-javascript.html Summary: An EMV QR code is a QR symbol carrying an EMVCo merchant-presented TLV payload with a CRC-16 checksum — the format under Pix, PromptPay, UPI and SGQR. Build one in JavaScript with bwip-js, scan one with your camera or from an image using Dynamsoft Barcode Reader, and see the wallet it drives. Author: Xiao Ling Published: 2026-10-15 (updated 2026-10-16) Topics: EMV QR, QR Code, Payment, TLV, CRC-16, Barcode Reader, bwip-js, JavaScriptThe QR code on a street vendor’s payment sign, the screen at a supermarket checkout, and the invoice QR on a utility bill usually carry the same thing: an EMV QR code — a QR symbol whose payload follows the EMVCo QR Code Specification for Payment Systems (merchant-presented mode). The payload is not free text; it is a flat run of tag-length-value fields in a fixed order, ending in a CRC-16 checksum, and that envelope is what Pix in Brazil, PromptPay in Thailand, UPI in India, SGQR in Singapore and DuitNow in Malaysia all build on. This article builds a conformant payload in the browser with bwip-js , renders it as a QR Code at the specification’s error-correction level, then reads it back with Dynamsoft Barcode Reader and parses it the way a payment app would — field by field, checksum first. What you’ll build: a browser-side EMV QR generator that assembles the TLV payload and its CRC-16 checksum from a form (static and dynamic codes, any ISO 4217 currency, randomized test merchants), verifies its own output by decoding the rendered symbol back, and a companion scanner that takes any payment QR — from the live camera, an image, a screenshot, or a pasted payload string — and produces the named field list, the checksum verdict, and the payment screen a wallet would show. ## Key Takeaways - An EMV QR payload is a flat TLV stream : every field is a two-digit tag, a two-digit decimal length, and exactly that many characters of value — no delimiters. The length says where the next field starts, which also caps any single value at 99 characters. - The stream ends with tag 63: a CRC-16/CCITT-FALSE checksum (polynomial 0x1021 , initial value 0xFFFF ) computed over the payload including the literal 6304 header but not the four hex characters it protects. Computing it over the wrong range is the most common implementation bug, and it produces a code that renders fine and is rejected by every wallet. - Top-level objects must appear in ascending tag order , and tags 26–51 plus 62 are nested templates — their values are sub-TLV streams built with the same rules one level down. - A static code (tag 01 = 11 ) must omit the amount and lets the payer type it; a dynamic code (tag 01 = 12 ) carries the amount in tag 54 and is minted per transaction. EMVCo requires QR error-correction level M for payment symbols. - Encoding and decoding are different problems: bwip-js draws the symbol, Dynamsoft Barcode Reader proves it. Decoding the rendered image back and comparing it byte for byte is what turns “the QR looks right” into a checkable statement. ## Common Developer Questions ### Is an EMV QR code a different barcode type from a normal QR code? No. To a scanner it is an ordinary QR Code (ISO/IEC 18004) carrying a specific text payload — every EMV QR decodes as a plain QR string starting with 0002 . The EMV part is the payload grammar: TLV fields in ascending tag order with a CRC-16 trailer. That is why the demos here encode with bwip-js (a QR Code at error-correction level M) and decode with Dynamsoft Barcode Reader on its default template; the payment semantics live entirely in the parse. ### How is the EMV QR checksum calculated, and why do valid-looking codes fail? The checksum is CRC-16/CCITT-FALSE over the payload up to and including the 6304 header that introduces it, written as four uppercase hex characters — for the demo’s dynamic sample the payload is 174 characters and the checksum is 40D2 . The classic failure is computing the CRC before appending 6304 , or over the wrong range: the result renders as a perfectly scannable QR that every wallet rejects, and nothing on screen tells you why. The demo’s tampered sample makes the failure visible — an amount edited from 12.50 to 99.99 still scans, but the parser reports that the code says 40D2 while the content computes to AB69 . ### What is the difference between a static and a dynamic EMV QR code? Tag 01 (point of initiation method) decides: 11 is static — one printed sticker that carries no amount, so the payer types the figure in their wallet app — and 12 is dynamic — minted per transaction, carrying the amount in tag 54 and, in practice, a per-transaction reference in tag 62 that the merchant reconciles against. A static code that includes an amount, or a dynamic code without one, violates the spec; the generator in this article validates both directions as you type. ### Can a generated EMV QR code be used to make a real payment? No. Real payment QR codes carry a merchant account registered with an acquirer or a national scheme inside tags 26–51 — a GUID such as BR.GOV.BCB.PIX for Pix or an AID-style identifier for card networks — and the wallet resolves that account to somewhere money can move. The generated codes here use fictional identifiers like com.dynamsoft.demo , which is exactly what makes them safe test vectors: wallets decline them, and that is the desired behavior for test data. ## Online Demo - Generator: https://www.dynamsoft.com/codepool/demos/emv-qr-generator/ - Scanner: https://www.dynamsoft.com/codepool/demos/emv-qr-scanner/ Both run entirely in your browser. The generator assembles payloads and renders symbols locally; the scanner decodes locally with Dynamsoft Barcode Reader — from the live camera or from an image — and nothing is uploaded. ## Demo Video: From Form to Payment QR, and Back The first video walks the generator: type a merchant name and watch the symbol and its payload re-emit on every keystroke, randomize into a different valid merchant with the changed fields highlighted, then verify the round trip — the rendered symbol is decoded back and matched byte for byte. The second video walks the scanner: the camera locks onto a dynamic payment code and the result panel opens with the checksum-verified field list, a simulated wallet turns those fields into a payment confirmation and a mock receipt, and the tampered sample — the amount edited from 12.50 to 99.99 — fails the checksum visibly in red. ## Prerequisites - A modern browser. The generator’s payload assembly and rendering are fully client side; decoding needs a secure context (HTTPS or localhost) for license activation, and live camera scanning additionally needs camera permission. - A Dynamsoft Barcode Reader license for your own deployment. The hosted demos activate their Codepool license automatically. Get a 30-day free trial license for Dynamsoft Barcode Reader. ## The Payload: Tag, Length, Value An EMV QR payload looks like noise until you see the split. Every field is three parts — a two-digit tag, a two-digit decimal length, and exactly that many characters of value — and the fields run together with nothing between them: Three rules do most of the work: - Ascending tag order. Top-level objects are emitted from small tags to large ones; the form does not choose the sequence, the model does. - The two-digit length caps values at 99 characters. A 26-character merchant name cannot be expressed, which is why the generator counts characters against EMVCo’s own limits (25 for the name, 15 for the city) as you type. - Tags 26–51 and 62 are templates. Their value is itself a TLV stream: tag 26 carries the merchant account (a scheme identifier plus scheme-specific fields), and tag 62 carries additional data such as the bill number (sub-tag 00) and the reference label (sub-tag 05) that a payment is reconciled against later. ## Step 1: Encode the Fields in Tag Order The shared model ( emv-model.js , loaded by both demos) owns the format so the generator and the scanner cannot drift apart. The TLV primitive is four lines: The builder then emits the objects it was given, in ascending order, nesting the merchant account template and the additional-data template as it goes: A static code is the same builder with pointOfInitiation: '11' and no amount — the generator hides the amount input in that mode so a stale value cannot leak into the payload. ## Step 2: Seal the Payload with CRC-16/CCITT-FALSE The checksum is CRC-16/CCITT-FALSE: polynomial 0x1021 , initial value 0xFFFF , no reflection, no final XOR. The subtlety is the range — the CRC covers the payload including the 6304 header that introduces it, and not the four hex characters it protects: Two anchors say this implementation is right before any wallet sees it. The canonical CCITT-FALSE test vector holds: CRC("123456789") must be 29B1 . And a published MasterCard example payload — the Secure-Card-on-File sample from their developer docs — parses cleanly, with our computed checksum matching the 6F6D the example ships with. The shared model carries 51 unit tests covering both anchors, the round trips, and the tamper cases; run them with node emv-model.test.js . ## Step 3: Render the Symbol at Error-Correction Level M EMVCo specifies QR error-correction level M for payment symbols, so the renderer passes it explicitly along with one option that is easy to miss: The backgroundcolor is not cosmetic. Without it bwip-js leaves the background transparent ; on a white page that looks identical, but canvas.toDataURL() keeps the alpha channel, and a decoder composites transparent onto black — the whole symbol reads as one dark rectangle and decodes to nothing. A white background and an intact quiet zone are both required for a symbol to decode, which is why the stage around the canvas is plain white. ## Step 4: Read the Symbol Back with Dynamsoft Barcode Reader A QR that renders is not evidence of anything — it looks identical whether the payload is a valid payment QR or a truncated string of digits. So the generator offers a round trip: click Verify it scans , and the page decodes its own canvas and compares the text against the payload that produced it. Two design points from the demo are worth keeping. First, the reader activates lazily — building and rendering a payload needs nothing but bwip-js, so the SDK loads only when the visitor asks for verification, and a generator that phoned home on page load for a feature nobody clicked would be the wrong trade. Second, a text match alone is not the verdict: the demo parses the decoded string as EMV afterward, because a matching string with a broken checksum is still not a payment QR. Only a byte-for-byte match plus a verified CRC turns the strip green. ## Step 5: Parse a Payment QR Like a Wallet Does The scanner is the same model run backwards, and its first rule is the one that matters: the checksum runs before anything else . Input comes from the live camera, from an uploaded or pasted image, or from a payload string typed straight into the page — and the camera path reads QR symbologies only, so a Code 128 on the same shelf label cannot win the decode race and pose as the payment code the visitor aimed at. A payload that fails the CRC is reported as tampered or not an EMV QR at all, and its fields are never shown as if trustworthy. A payload that passes gets the full treatment — every top-level tag named, nested templates indented under their parents, the currency and merchant category resolved from their ISO codes, and a summary sentence a payer would recognize: Requests USD 12.50 to DYNAMSOFT DEMO STORE (grocery stores / supermarkets), reference INV-2026-0042, CRC verified. The demo then answers the “so what” that a field table cannot: a simulated wallet builds its payment screen from exactly the fields parsed above. Confirming produces a mock authorization receipt — an auth code, and an explicit statement of where tag 62 goes: the reference travels back with the payment so the merchant reconciles the settlement against that bill number. No payment provider is contacted; the point is that the structured data drives a real UI. ## What a Tampered Code Looks Like The bundled third sample is a dynamic code whose amount was edited from 12.50 to 99.99 after the checksum was computed. It still scans — the QR itself is well formed — and that is the point: the damage is invisible to any reader that does not check the CRC. The scanner rejects it before showing a single field as trustworthy. This is the attack the checksum exists for — swapping a merchant’s counter sticker for a fraudster’s is a real, documented fraud pattern, and a photographed code carries no other integrity signal. ## Common Issues & Edge Cases The checksum covers the wrong range. Computing the CRC before appending 6304 , or over the payload including the four checksum characters, produces a code that renders and scans and fails in every wallet. Seal the payload in one function, the way sealWithCrc does above, and the range cannot drift. The QR renders but nothing decodes it. Check the background first: a transparent-background PNG composites onto black in a decoder. Pass backgroundcolor: 'FFFFFF' to bwip-js (Step 3), and keep the quiet zone. A field silently truncates or throws. TLV lengths are two decimal digits, so any value over 99 characters is inexpressible. The model throws rather than truncating; catch it and surface the limit next to the input, as the generator does with live character counters. A static code carries an amount, or a dynamic one does not. Both violate the spec and both are common. The validator treats them as errors with the rule spelled out — a static code leaves the amount to the payer; a dynamic code must carry it in tag 54. Real-world payloads do not always follow the named sub-tags. A published MasterCard example nests its bill number under sub-tag 03 rather than the sub-tag 00 the specification names. The scanner shows what is literally present instead of silently renumbering it — exactly what a parser facing production traffic needs to do. The currency code means nothing to a human. Tag 53 carries ISO 4217 numeric codes ( 840 , not USD ). Resolve them for display; the demo generates its currency table from the official ISO list rather than a hand-typed subset, and the difference shows up as 978 = EUR instead of “unknown”. ## Real-World Constraints The demos cover merchant-presented mode only . Consumer-presented mode — the payer’s phone shows the QR and the merchant scans it — is a different payload structure and deliberately out of scope. The merchant account identifiers in the generator are fictional, so wallets decline these codes; that is what makes them safe test vectors. And the spec is the authority: this article covers the fields a working demo needs, not the full EMVCo specification, which is worth reading directly if you are building production payment software. ## Conclusion An EMV QR code is a QR Code wearing a contract: TLV fields in ascending tag order, nested templates for scheme data, and a CRC-16 seal that makes tampering detectable. The build is mostly formatting with one piece of real arithmetic, and the two halves reinforce each other — writing the parser alongside the generator is what makes every generated code checkable, and the round trip is what makes “it scans” a statement you can verify instead of assume. Point the generated codes at the scanner, watch a wallet consume the fields, and the format stops being a wall of hex. ## Source Code Get the complete sample project source code on GitHub: - EMV QR Code Generator (examples/emv-qr-generator) - EMV QR Code Scanner (examples/emv-qr-scanner) ### How Much Damage Can a QR Code Take? A Visual Guide to QR Error Correction Levels URL: https://www.dynamsoft.com/codepool/qr-code-error-correction-visualizer.html Summary: A QR Code recovers damage through Reed-Solomon parity, not magic: level L repairs roughly 7% of its codewords and level H roughly 30%. Build, damage, and decode QR codes in the browser with a new interactive error correction visualizer powered by Dynamsoft Barcode Reader. It also rebuilds a damaged code you upload, when the data survives, as a symbol you can download. Author: Xiao Ling Published: 2026-10-11 (updated 2026-11-03) Topics: QR Code, Error Correction, Reed-Solomon, Barcode Reader, JavaScriptA damaged QR code usually still scans — not because QR codes are magically robust, but because every symbol carries Reed-Solomon parity codewords that a scanner can use to rebuild what a scratch, a glare, or a coffee mug destroyed. How much damage a QR code can take has a concrete answer: it depends on the error correction level. Level L spends about 7% of its capacity on parity and recovers roughly 7% of its data, M about 15%, Q about 25%, and H about 30% — measured in codewords , not in pixels or modules, which is the detail most explanations skip. This article makes that budget visible: we build QR symbols in the browser with an encoder that exposes the codeword behind every module, damage them on purpose, and decode the results with Dynamsoft Barcode Reader to see exactly where each level stops recovering. What you’ll learn: how a QR Code splits its payload into data and parity codewords across Reed-Solomon blocks, why the repair budget is ⌊EC/2⌋ corrupted codewords per block, why damage to finder or timing patterns sits outside that budget entirely, and how the four error correction levels compare when the same payload is damaged step by step and decoded live. ## Key Takeaways - QR error correction operates on codewords, not modules : a block of e Reed-Solomon parity codewords repairs up to ⌊e/2⌋ corrupted codewords, so one scratched module can consume a whole codeword from the budget. - The four levels spend very different shares on parity: for a 35-character URL, auto version selection produces 15 parity codewords at level L (21% of the symbol) but 88 at level H (66%), raising the repair budget from 7 to 44 codewords. - Damage to function patterns — finder, timing, alignment, format, or the dark module — is uncorrectable by design: those modules carry no parity, and a scanner that cannot find or orient the symbol never reaches error correction. - In a seeded damage sweep on this demo, level M decoded up to 2.6% module damage and failed from 3.8%, while level H still decoded at 6.0% and failed from 7.5% — more than twice the survivable damage, measured with the same decoder on the same payload. - Every claim above is reproducible in the browser: the visualizer counts real corrupted codewords per block from the encoder’s own placement map, not a pixel-level guess. - A damaged symbol can be rebuilt, not just read : when the data survives, the demo writes the corrected codewords back into a symbol — same version, same level, same mask — and hands it back as PNG or SVG once its own reader confirms the payload. That is a redraw from codewords, not a restoration of the original pixels. ## Common Developer Questions ### What do the QR error correction levels L, M, Q, and H mean? L, M, Q, and H are the four recovery levels defined by ISO/IEC 18004: a symbol at level L can repair roughly 7% of its data, M about 15%, Q about 25%, and H about 30%. The percentage is bought with Reed-Solomon parity codewords — level H spends about two thirds of a typical symbol on parity — so a higher level means a larger symbol for the same payload. ### How much damage can a QR code take before it stops scanning? It depends on where the damage lands relative to the codewords. A Reed-Solomon block of e parity codewords corrects up to ⌊e/2⌋ corrupted codewords per block; damage that hits more codewords than that in any one block is beyond repair. In the damage sweep shown below, a version-3 symbol at level M stopped decoding between 2.6% and 3.8% module damage, while a version-5 symbol at level H kept decoding up to 6.0% module damage — decoded by Dynamsoft Barcode Reader at default settings on the same payload. ### Why does a small scratch on a QR corner break the whole code? The three corner squares are finder patterns, and the lines between them are timing patterns — together with the format information and the dark module they form the scaffolding a scanner uses to locate, orient, and sample the symbol. These modules carry no parity codewords, so error correction cannot rebuild them; if the scaffolding is unreadable, the scanner never gets far enough to attempt Reed-Solomon repair. ### Which error correction level should I use? Use level H or Q when the symbol will face real-world abuse — laser engraving, outdoor signage, fabric printing, or packaging that gets handled — and pay for it with a larger symbol. Use M for general print-and-screen use, and L only when the payload is long and the surface is controlled, such as a URL on a clean screen. The demo’s level comparison shows the parity and repair counts for all four levels at the current version, so you can read the trade-off instead of guessing it. ## Online Demo https://www.dynamsoft.com/codepool/demos/qr-error-correction-visualizer/ ## Demo Video: Damaging and Decoding QR Codes Live The video walks through the core loop: paint damage on the symbol until level M gives up, clear it, run a seeded damage sweep, then repeat at level H and watch the same payload survive far more abuse. ## Prerequisites - A modern browser. The QR encoder runs entirely client side; decoding needs a secure context (HTTPS or localhost) for license activation. - A Dynamsoft Barcode Reader license for your own deployment. The hosted demo activates its Codepool license automatically. Get a 30-day free trial license for Dynamsoft Barcode Reader. ## QR Anatomy: the Parts of a Symbol Every region of a QR symbol has a name, and the vocabulary matters because each part fails differently. The diagram below colors each region of a real version-3 symbol; the demo’s QR anatomy panel renders the same view for whatever symbol you have encoded, with every term hoverable on the live grid. Term | What it does | If it is damaged | Module | One black or white square; a version-3 symbol is 29×29 of them | One damaged module can corrupt a whole codeword | Codeword | 8 modules read as one byte — the unit error correction counts | Corrupted codewords consume the repair budget | Finder patterns | The three large squares the scanner uses to locate and orient the symbol | No parity protects them; often fatal | Separators | The one-module light ring around each finder pattern | Finder edges blur into the data region | Timing pattern | The alternating stripe in row 6 and column 6; sets the grid spacing | Sampling drifts, modules get misread | Alignment pattern | The small square lower right; corrects distortion on larger symbols | Skewed sampling on big symbols | Format information | 15 bits, stored twice: the error correction level and the mask | Both copies lost → nothing to decode | Version information | 18 bits, versions 7 and up only: the symbol size | Mis-sized grid on large symbols | Dark module | One always-dark module; a fixed orientation anchor | Minor, but the standard requires it | Data codewords | The payload — 44 of them in this symbol | Corruption consumes the repair budget | Error correction codewords | The Reed-Solomon parity — 26 of them here | Corruption consumes the same budget | Quiet zone | Four white modules on every side | Scanner may not separate symbol from background | ## How a QR Code Spends Its Redundancy A QR symbol does not store “text with a few spare pixels”. The payload is packed into 8-bit data codewords , each block of data codewords gets a run of Reed-Solomon parity codewords computed over it, and the combined sequence is interleaved across blocks and laid onto the module grid in a zigzag order. When a scanner samples the grid, every module contributes one bit; eight modules make one codeword; and the Reed-Solomon decoder can rebuild a corrupted codeword as long as each block stays within its repair capacity. The structure view of the visualizer colors this machinery directly on the symbol: white cells carry data codewords, orange cells carry Reed-Solomon parity, and the blue-gray cells are function patterns — the collective name for the finder patterns, timing pattern, alignment pattern, format information and dark module in the anatomy table above. Click any module and the panel reports which codeword it belongs to, which block owns that codeword, and how many codewords the block carries. Two consequences follow directly from the picture: - The repair budget is per block. A block with e parity codewords corrects up to ⌊e/2⌋ corrupted codewords. Damage is not shared between blocks: if block 2 of 4 burns its budget, the symbol fails even when the other three blocks are pristine. - Function patterns sit outside the budget. They are the coordinates system of the symbol. Error correction repairs codewords, not scaffolding — cover a finder pattern and no amount of parity helps, because the scanner cannot establish where the data region even is. ## Step 1: Encode with the Codeword Map Exposed Most QR encoders hand you a bitmap and keep the internals. The demo uses a dependency-free encoder (ISO/IEC 18004 byte mode, versions 1–40, all four levels, standard mask search) that also returns the maps a structure view needs: the interleaved codeword index behind every module, the block split, and a per-module role map. For the demo’s 35-character default payload, auto version selection lands on version 3 at level L and M, version 4 at Q, and version 5 at H — the level costs size, which is the trade-off in action. ## Step 2: Turn Painted Damage into a Repair Budget When you drag across the symbol, each painted module flips to a stable random value — like a real scratch that repaints the surface. Because placement maps every module to its codeword, damage becomes bookkeeping: count the distinct codewords that own at least one damaged module, map each to its block, and compare the per-block tally against that block’s repair capacity. The meter treats a codeword as corrupted as soon as one of its eight modules is damaged — a deliberate upper bound, since a scratch can repaint a module with the value it already had. It is still exact about which codewords and which blocks are at risk, which is what a pixel-damage percentage cannot tell you. The same panel carries the lesson that hurts: cover a finder pattern — one of the three large corner squares from the anatomy table — or mangle the format information, the 15-bit field that tells the scanner which level and mask were used, and the meter flags function-pattern damage — 64 modules in this shot — with the note that error correction cannot repair them. The budget bars may still be half empty when the symbol becomes unscannable. ## Step 3: Decode the Damaged Render with Dynamsoft Barcode Reader The damaged render is decoded the way a camera would see it: the clean module grid plus the damage, rendered onto one canvas and passed to Dynamsoft Barcode Reader as a raw frame. Canvas ImageData stores pixels in RGBA byte order, which is exactly the byte order the SDK calls IPF_ABGR_8888 — so the buffer goes in directly: The decoder runs on your device; the first decode downloads the WebAssembly engine (about seven seconds on this connection), and every later decode of a symbol this size settles around 30–60 ms — fast enough to decode automatically after every change. ## What the Sweep Shows: Where Each Level Stops The damage sweep is the experiment that makes the levels comparable. It accumulates seeded random damage on the encoding region in ten steps from 0% to 25%, decodes after each step, and logs the module damage percentage against the outcome. Every run uses fixed seeds, so the table is reproducible. At level M (version 3, one block, 26 parity codewords, 13 repairs), the payload decoded intact up to 2.6% module damage and failed from 3.8% onward: At level H (version 5, four blocks, 22 parity codewords per block, 44 repairs in total), the same payload still decoded at 4.5% and 6.0% module damage and failed from 7.5%: Read the two tables side by side and three things stand out (all levels and versions here are the ones auto-selected for the 35-character payload shown in the anatomy diagram): - H survived more than twice the module damage of M in this sweep — 6.0% versus 2.6% at the last successful decode — because its repair budget is 44 codewords against 13, on a payload that stayed the same size. - The failure boundary is a budget, not a percentage. Random damage lands on parity codewords as well as data codewords, and a corrupted parity codeword consumes the budget exactly like a corrupted data one. That is why the percentages look small: only about a third of the symbol carries data, and every hit counts. - The boundary moves with the payload. Switch the error correction level and the auto-selected version grows; the parity count, the block count, and therefore the sweep outcome all change with it. The comparison bars under the symbol show the four levels’ parity and repair counts for the current version. ## Step 4: Rebuild a Damaged Symbol You Did Not Generate Everything above starts from a symbol this page encoded itself, so it knows every module. The last panel starts from a photograph instead: drop in a QR code someone sent you, and the page measures it — then, when the data is still there, hands back a symbol you can print. Three things happen, in order. 1. The reader gets three escalating passes. The default settings run first. If they find nothing, the page retries with the modes built for physical damage: BarcodeComplementModes ( BCM_GENERAL ) completes missing positioning patterns and DeformationResistingModes ( DRM_GENERAL ) straightens a distorted symbol. If that fails too, it builds prepared copies of the image — Otsu-binarized with a 3×3 closing pass over the pinholes, and the same copy turned by ±45° — and runs the damaged template on each. This is not a detail. On the sample photo used for this section — a printed symbol with one corner torn through the bottom-left finder pattern — the default template returned zero results, and the second pass returned the payload at 98% confidence. The third pass exists for the two failures neither template can reach: a postal label whose ink is pinholed, and the same code wrapped 45° around a can. Both read only after the binarize-and-turn, and when that is what happened the report says so — the damage percentage is omitted rather than faked, because the grid was never locked on the original image. Two footnotes before you copy it: initSettings() replaces the whole template set, so the moment you register a custom document the preset names ( ReadBarcodes_Default ) stop resolving and you have to register your own default template alongside it; and the localization modes must be named explicitly (connected blocks, lines, statistics, scan directly, neural) inside the damaged template, or that second pass finds nothing on a symbol the first pass also missed. 2. The grid locks onto the symbol. The reader returns four corners in location.points , clockwise from the top-left, and those corners drive a homography: each candidate version is sampled and scored against its finder and timing patterns. A damaged symbol needs one concession here. A torn finder pattern scores about 0.80 where an intact one scores near 1.0, and the demo’s threshold for a grid it found on its own is 0.82 — so when the corners came from a successful decode, the threshold drops to 0.6. A decode is its own proof that the symbol exists; the pattern score only has to confirm the grid is not wildly off. 3. The symbol is written back, not re-encoded. There are two sources of codewords, in order of preference. First the page’s own Reed-Solomon decode of the sampled modules, which is the honest measurement path because it knows exactly which codewords it repaired. When the damage sits on the data region and no block verifies, the codewords come from details.codewords instead — a decode means the reader already recovered the whole stream, so the symbol can be drawn from that. Two API details were measured rather than assumed: details.codewords is the full raw sequence including parity, and details.errorCorrectionLevel is the SDK’s own enum, not the format field’s two bits — against known symbols it reads 0=H, 1=L, 2=M, 3=Q . Either way the output is a module matrix, and everything the standard fixes by version is redrawn from that version instead of copied from the blur: finder patterns, separators, timing, alignment, the dark module, version information, and both copies of the format field. The format field is the one that bites — a symbol whose format field is unreadable gets decoded by brute force, and the rebuilt symbol needs a valid format field or its own reader will reject it. Then the page hands the rendered pixels back to the reader and compares the payload. The download stays disabled until the two agree: a rebuild its own reader will not accept is not a recovery, and the demo does not offer it. Two limits worth stating plainly. The rebuilt image is a redraw from codewords, not a restoration of the original pixels — same version, same level, same mask, same payload, different paper. And if the finder patterns are damaged past the point where anything locates the symbol, no grid locks and there is nothing to rebuild; the page says so rather than guessing. ## Common Issues & Edge Cases - The percentage says fine but the scan fails: module damage and codeword corruption are different currencies. One damaged module can flip a whole codeword, and damage concentrated on a single block overloads that block while the others look healthy. Watch the per-block budget bars, not just the headline percentage. - Covering a finder pattern breaks the symbol instantly: finder, timing, alignment, format, and version modules carry no parity. The demo flags function-pattern damage separately because no Reed-Solomon budget applies to it. - The first decode takes seconds, later ones take milliseconds: the reader downloads its WebAssembly engine on first use. Preload it once on page load if your application decodes on a user action with no patience for a cold start. - Painted damage can be a no-op: the brush repaints a module with a stable random value, which sometimes equals the value the module already had. The budget meter still counts the codeword as at risk — an upper bound by design. - Capture-defect percentages are estimates: noise, blur, low contrast, occlusion, crop, shadow, and tilt are rendered onto the canvas, and the corruption estimate samples each module’s centre against its intended value. Module damage from the brush and sliders is exact; pixel-level damage is an estimate. - A code a human can read but the reader calls unreadable: the default template is the fast path and it gives up on a torn finder pattern. Before concluding the image is dead, run the second pass with complement and deformation resisting — on the sample in Step 4 the defaults returned nothing and the second pass returned the payload. - The recovered symbol’s download button is disabled: that is the re-read gate, not a bug. The rebuilt symbol did not come back with the same payload, which almost always means the damage was past the budget or the grid lock picked the wrong version. ## Real-World Constraints The sweep numbers in this article are measurements from this demo, this payload, and this reader: Dynamsoft Barcode Reader at default settings, decoding rendered images, with damage applied at the module level. Other readers use different localization and sampling strategies; printing, scanning, and photographing a symbol changes module geometry in ways the canvas render does not model; and Reed-Solomon erasure decoding — which a scanner can apply when it knows where the damage is — can recover more than the ⌊e/2⌋ error bound under some conditions. Treat the sweep as a way to understand the mechanism and compare the levels, not as a certified damage rating for your print layout: if you need a print-quality verdict, that is a job for an ISO 15415 verifier, not a browser tool. The recovered symbol belongs to the same caveat: it is a redraw from codewords, geometrically exact but a new print rather than a repair of the old one, and it is only produced when the data survived in the first place. ## Conclusion QR error correction is a concrete, countable resource: parity codewords, split into blocks, each repairing up to half its own count. Once you can see which codeword sits under which module, “how much damage can a QR code take” stops being folklore — you can paint the damage, watch the per-block budget drain, and read the failure boundary off a real decoder. The same mental model explains the practical rules: higher levels buy recovery with symbol size, function patterns are precious because nothing repairs them, and a scratch that lands on a parity codeword costs as much as one that lands on data. From here, the natural next step is the Barcode Structure Diagram , which annotates the rest of the symbol the same way, or the Barcode & QR Code Generator if you need degraded test datasets at scale. ## Source Code Get the complete sample project source code on GitHub ### How to Generate and Scan VIN Barcodes with JavaScript (Code 39, Code 128, QR Code and Data Matrix) URL: https://www.dynamsoft.com/codepool/vin-barcode-generator-scanner-javascript.html Summary: Generate and scan VIN barcodes in JavaScript: build a valid 17-character VIN with the North American check digit calculated as you type, render it as Code 39, Code 128, QR Code or Data Matrix with bwip-js, and decode it with Dynamsoft Barcode Reader — importing the 18-character form, verifying the check digit, and parsing the WMI, model year and plant code. Author: Xiao Ling Published: 2026-10-10 (updated 2026-10-10) Topics: VIN, Code 39, Barcode, Barcode Reader, DBR, JavaScript, HTML5, WebA Vehicle Identification Number (VIN) is the 17-character code that identifies one specific vehicle — the automotive equivalent of a serial number, stamped on the dashboard, door jamb and registration papers. Fleet check-ins, insurance claims, dealer service lanes and parts catalogs all start with capturing it accurately. This article builds the barcode route end to end in the browser: a generator that produces valid VIN barcodes for testing, and a scanner that decodes them back into structured data — both working demos, with the full source on GitHub. A note on scope before the code. VINs are captured by two very different technologies: barcode decoding and optical character recognition (OCR). Some vendors offer VIN OCR that reads the stamped characters directly. Dynamsoft’s SDK is a barcode reader — it decodes VINs from barcode symbols and has no VIN OCR model , which is why this article (and the demos it ships with) is barcode-only. The two approaches are complementary rather than competing: if your users photograph the stamped VIN on a bare chassis, you need an OCR product; if the vehicle carries a label with a barcode — as every North American vehicle does, and most European paperwork does — a barcode scan is the faster, more deterministic capture path, because a decode always yields the same 17 characters and the check digit lets you validate it on the spot. Try it online: the VIN barcode generator and the VIN barcode scanner are both hosted on Codepool, no sign-up needed. ## What you’ll build Two single-page JavaScript apps that share one VIN model: - A generator : type a VIN (or click Random), pick a standard preset — North America (FMVSS 115) or Europe (ISO 3779) — and render the symbol as Code 39, Code 128, QR Code or Data Matrix with bwip-js. The check digit recalculates as you type, with a one-click fix. - A scanner : decode VIN barcodes with Dynamsoft Barcode Reader from a camera or an image, strip the 18-character import-prefix form, verify the check digit and parse the WMI, region, model year, plant code and serial number. ## Key Takeaways - A VIN barcode decodes to 17 characters from A–Z and 0–9 , minus I , O and Q — and sometimes 18 : a leading I import marker that the scanner strips before validating. - The check digit in position 9 covers every other position. It is mandatory in North America (FMVSS 115) and China, absent in Europe — so a mismatch is an error under the North American preset and a non-issue under the European one. - The check digit covers positions 1–8 and 10–17: compute it only after the tail of the VIN (year, plant, serial) is final, or the weights land on the wrong positions. - Dynamsoft Barcode Reader is barcode-only: there is no VIN OCR in the SDK, so barcode presence on the label is a hard requirement for this route. ## Common Developer Questions ### Does Dynamsoft Barcode Reader support VIN OCR? No. Dynamsoft Barcode Reader decodes VINs from barcode symbols — Code 39, Code 128, QR Code and Data Matrix. The SDK has no OCR model for the stamped or printed VIN characters. If your capture scenario has no barcode on the vehicle, you need a dedicated OCR product; the rest of this article covers the barcode route. ### Which symbology should a VIN barcode use? On North American vehicle labels, Code 39 — that is what FMVSS 115 expects. European labels and import paperwork commonly use Code 128, and a 17-character VIN also fits a QR Code or Data Matrix. The generator below supports all four and the scanner accepts all four. ### Why does my scanner return 18 characters for a VIN? A VIN barcode may carry a leading I before the 17 real characters — an import marker. I is legal in Code 39 but illegal in a VIN, which is how you know it is a marker: strip it before validating. The scanner in this article does this automatically and reports the strip in the result. ## Prerequisites - A modern browser with WebAssembly support (Chrome, Edge, Firefox, Safari). Camera scanning additionally needs HTTPS or localhost and camera permission. - A Dynamsoft license. The hosted demos activate one automatically; for your own deployment, Get a 30-day free trial license . - The bwip-js CDN bundle for the generator side. ## Step 1: Model the VIN — check digit, year codes, regions Everything downstream shares one set of pure functions in vin-model.js (a UMD module used by both demos, so the rules cannot drift between generator and scanner). The check digit: transliterate each character (digits keep their value; A=1 … H=8 , then J=1, K=2, L=3, M=4, N=5, P=7, R=9 , then S=2 … Z=9 ), multiply by the weights 8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2 — position 9 gets weight 0 because that is the check digit itself — sum, mod 11, and a remainder of 10 is written as X : The model year code (position 10) repeats every 30 years, so one character maps to two candidate years — W is 1998 or 2028. The demos show both rather than guessing: ## Step 2: Generate — random VINs that are actually valid A random VIN has a trap worth calling out: the check digit covers every position except 9, so the placeholder string must already carry the final year, plant and serial characters before the check digit is computed . Compute it against a partially filled string and the weights land on the wrong positions — the demo’s first draft did exactly that, and the self-test caught it. Under the European preset the rule inverts: position 9 is a free character (the demo tosses in an X half the time, like real European VINs) and no check digit is computed at all. The generator UI recalculates position 9 as you type — under the North American preset a mismatch is an error with a one-click Fix button; under the European preset position 9 is shown but never judged — and the canvas redraws on every keystroke. There is no render button to forget: Rendering goes through bwip-js, with a white background baked into the exported PNG so the downloaded file matches what the page shows: ## Step 3: Scan — restrict the reader to VIN symbologies The scanner initializes Dynamsoft Barcode Reader from the dynamsoft-barcode-reader-bundle CDN package: Do not hand-write a template JSON for the format restriction — read a preset, change one field, write it back. A hand-written template is accepted by initSettings() and then rejected by startCapturing() with error [-10038] , because the engine validates the document as a whole. Format IDs in simplified settings take the numeric runtime mask, and those values are BigInt : Restricting the list is not only a speed win: a QR Code on a service booklet that happens to encode a URL will not compete with the VIN symbol. ## Step 4: Decode and strip the import prefix CaptureVisionRouter.capture() wants raw pixels, not an element — passing a canvas takes an internal path that can silently return no results. Build the DSImageData shape from getImageData() : The decoded string goes through the frame-character strip before validation, per the North American VIN barcode convention: Anything the scanner strips is reported in the result card, so a user can see why the decoded string did not look like a VIN: ## Step 5: Parse the decoded VIN One analyzer serves the scanner and the manual-entry box. A failed check digit is a warning, not a rejection : the rule is North American (and Chinese); a European VIN with a filler in position 9 is still valid under ISO 3779. The result card words it that way instead of declaring the VIN broken: Camera mode follows the same pattern as the other Codepool scanners: the Camera Enhancer pushes frames, and a MultiFrameResultCrossFilter with result deduplication keeps a steady shot from re-rendering the panel dozens of times. ## Common Issues & Edge Cases - A stamped VIN with no barcode cannot be scanned. The barcode route requires a symbol on the label; the bare stamped or engraved characters are out of scope for a barcode SDK (see the OCR note at the top). - The decoded value is 18–20 characters. Strip the leading I (18) or the frame digits (19/20) before validating — but report the strip, as the demo does. - The capture returns no results for a canvas. Pass raw DSImageData bytes instead of an element. - A European VIN reports a check-digit mismatch. It is a warning under this demo’s default; switch the generator to the Europe preset to see position 9 treated as a free character. ## Source Code Get the complete sample project source code on GitHub: examples/vin-barcode-generator and examples/vin-barcode-scanner in the javascript-barcode-qr-code-scanner repository. The generator runs anywhere with no SDK; the scanner needs your own Dynamsoft license outside dynamsoft.com. ### How to Read a Boarding Pass Barcode in JavaScript (IATA BCBP) URL: https://www.dynamsoft.com/codepool/read-boarding-pass-barcode-javascript.html Summary: Read the IATA BCBP barcode on a boarding pass in JavaScript with Dynamsoft Barcode Reader, then parse the Resolution 792 payload into structured fields — passenger, PNR, route, flight, seat, baggage and frequent flyer data — with nine structural checks and WebCrypto verification of the security section's ECDSA signature. Author: Xiao Ling Published: 2026-09-18 (updated 2026-09-23) Topics: Barcode, IATA BCBP, Boarding Pass, PDF417, Aztec, Data Matrix, JavaScript, Web, HTML5, DBRReading a boarding pass barcode is two problems, not one. The first is decoding the symbol: a printed pass carries PDF417, while Aztec Code, QR Code and Data Matrix appear on mobile passes and on printed passes from version 7 — and whichever symbol it is, it is often curved, glared or photographed at an angle. The second is understanding what came out: an IATA BCBP payload is a fixed-order binary layout, not a string you can split on commas. Dynamsoft Barcode Reader handles the first problem, including the symbologies and the difficult captures. The second is a parsing job with real substance to it: the payload is positional, and its optional sections are measured by three nested size fields. This article therefore pairs the two — the Reader finds and decodes the symbol, and bcbp.js , a small standalone parser that ships with the demo, turns the resulting string into named fields and verifies the security section’s signature when the pass carries one. What you’ll build: a browser-side boarding pass scanner — camera and image input, BCBP parsing across all four boarding pass symbologies, readable labels for the code lists, the scanned image shown beside the parsed fields, nine structural checks, signature verification with a Require signature switch, and a JSON export. ## Online Demo https://www.dynamsoft.com/codepool/demos/boarding-pass-scanner/ ## Demo Video ## Key Takeaways - Two jobs, two tools. Dynamsoft Barcode Reader locates and decodes the symbol; the BCBP field layout is read by bcbp.js , a standalone Resolution 792 parser shared with the companion generator. - A boarding pass carries a 2D symbol. PDF417 and MicroPDF417 on printed passes, plus Aztec Code, QR Code, Micro QR and Data Matrix on mobile and version-7 printed passes. Restrict the format mask to those and the reader stops reporting unrelated codes. - Dynamsoft.DBR.EnumBarcodeFormat values are BigInt in 11.x. var mask = 0; mask |= v throws Cannot mix BigInt and other types ; the accumulator has to start at 0n . - The Aztec enum member is BF_AZTEC , not BF_AZTEC_CODE . A misspelled name narrows the mask silently and that symbology simply never matches. - The variable field is not self-delimiting. Each leg ends with a two-hex-digit byte count (item 6), and inside that field two more counters (items 10 and 17) size the conditional blocks — so a parser follows three nested counters rather than looking for a terminator. - A transparent PNG can fail to decode. Canvas-exported symbols carry an alpha channel, and (0,0,0,0) read as RGBA is black — which fills the quiet zone with ink. Composite onto white first. - Show the source image beside the parse. Parsed fields are hard to trust on their own; with the picture next to them, a wrong value is immediately attributable to a bad crop or a bad encode rather than to the reader. - A signature is evidence, not identity — and requiring one is the reader’s policy. The security section (items 25–30) can carry an ECDSA P-256 signature; this scanner verifies it against the generator’s demo public key (green when it matches, red when it does not), and a Require signature switch turns an unsigned pass into a refusal. BCBP itself never demands any of it: a payload that parses proves the data is well formed, not that the reservation is real. - Verification strips the signature before checking it. Items 25–30 are cut off back to the end of the last leg, and the remaining bytes are what the public key is checked against — otherwise item 30 would be part of the message it signs. ## Common Developer Questions ### How do I read a boarding pass barcode in JavaScript? Decode the 2D symbol with a barcode SDK to get the payload string, then parse that string against the IATA Resolution 792 layout. In the browser, Dynamsoft Barcode Reader decodes PDF417, Aztec Code, QR Code and Data Matrix from a camera stream or an uploaded image; the payload is then split by fixed field widths, with three nested hexadecimal size fields telling you where each optional block ends. ### How do I turn the decoded BCBP payload into named fields? Use a Resolution 792 parser. Once the Reader has returned the payload string, the fields are fixed widths inside ordered blocks, and the optional sections are delimited by three nested hexadecimal size fields rather than by separators — so the parser walks the counters and slices each item. This article uses bcbp.js , the standalone parser the demo ships with, which also resolves the code lists (compartment J to Business (premium) , status 1 to Checked in ) and runs nine structural checks on the result. ### Which barcode symbologies appear on a boarding pass? Printed passes use PDF417 , and since Resolution 792 version 7 (2018) may also use Aztec Code, QR Code or Data Matrix . Mobile passes have used the 2D symbologies since version 2. Restricting the Reader to BF_PDF417 , BF_MICRO_PDF417 , BF_AZTEC , BF_QR_CODE , BF_MICRO_QR and BF_DATAMATRIX covers every boarding pass and avoids reporting unrelated codes in the same frame. ### Why does my code throw “Cannot mix BigInt and other types”? Dynamsoft.DBR.EnumBarcodeFormat values are BigInt in 11.x, because the format mask spans more than 32 bits and a JavaScript number cannot hold it. Build the mask with a BigInt accumulator: ### What does the scanner check besides decoding the barcode? Nine structural checks on the payload: the format code is M , the computed length equals the actual length, the leg count matches the data, a version marker is present and recognised, each airport code is three letters, each Julian date is within 001 – 366 , each seat follows the row-plus-letter form, each leg’s declared block size agrees with the data present, and — when a security section is present — the byte count item 29 declares matches the item 30 data actually in the payload. These catch a payload that decoded correctly but was not written correctly. The signature verdict reported in Step 8 is a separate question: it answers whether the bytes were edited , not whether they are well formed. ### How do you verify a boarding pass signature in JavaScript? Import the issuer’s public key with WebCrypto ( crypto.subtle.importKey('spki', ...) for an ECDSA P-256 key), cut items 25–30 off the payload back to the end of the last leg, decode item 30 from base64 into its raw 64 bytes, and call crypto.subtle.verify() over those stripped bytes — the same trimming on both sides is what makes the comparison meaningful. In this demo the whole thing is Bcbp.verifySecurityData(payload, DEMO_PUBLIC_KEY) , which resolves to one of five states: ok (signature matches), bad (edited, truncated or signed with another key), none (no security section — nothing to verify, not an error), unsupported (WebCrypto unavailable) or error (the payload did not decode at all). ## Prerequisites - A Dynamsoft Barcode Reader license key. The 24-hour trial key works for a first run; a 30-day free trial license covers development and testing. - A browser with camera access for live scanning, or any browser for image upload. - A local web server. The page loads sibling folders, so file:// will not do. - Some boarding pass images. The demo ships seven with known payloads, produced by the boarding pass generator . ## Step 1: Load the SDK and restrict the symbologies Activate the license before creating any component, then load only the module you need: The format mask is where both traps live — the BigInt accumulator and the enum member name — so it is worth writing defensively: The missing list is worth keeping. BF_AZTEC_CODE looks plausible but is not the real member name, and a name that does not exist on the enum is undefined — which ORs to nothing and excludes that symbology without raising anything. With the check in place the console says exactly what is wrong: Applying the mask goes through the simplified settings of the preset template: Note the try / catch . Narrowing the symbologies makes the reader faster and cuts spurious detections, but it is not required for correctness, so a failure to build the mask should degrade to the preset default instead of taking the whole page down. ## Step 2: Decode from an image, and composite onto white Camera frames flow through the router continuously. An uploaded image is different: it is decoded on demand with capture() , which takes an image object rather than a file. The shape matters — it must be the same one the SDK builds internally when its own image view hands over a picked file: Before getImageData , fill the canvas white: That last comment is not hypothetical. A symbol exported from an HTML canvas has a transparent background unless you filled it. The demo’s own sample images originally failed to decode for exactly this reason: the file looked right in an image viewer, and the reader saw a solid black rectangle. Every “transparent” pixel is (0,0,0,0) , and the alpha channel is ignored on the path into the SDK. The scanner takes either input. Upload mode accepts a file, a drop or a clipboard paste, and ships the seven generated samples so you can try it without a boarding pass to hand: ### Showing the image next to the parse Parsed fields on their own are hard to trust. When the panel also shows the picture the barcode came from, a wrong field is immediately attributable — a blurry crop, the wrong half of the pass, or a genuinely misencoded symbol. The image path already has the source, so passing it through is one extra argument; the camera path can produce one too by snapshotting the viewfinder: The image is bounded by its own aspect ratio rather than stretched, so a tall paper pass and a wide bare symbol both stay readable, and clicking it opens the full-size view: ## Step 3: Split the work between the Reader and the parser It is worth being precise about who does what, because the division shapes the whole demo: Step | Who does it | Locate and decode the symbol, whatever the capture conditions | Dynamsoft Barcode Reader | Split the string into items, follow the nested size fields, decode the code lists | bcbp.js | The Reader’s job is the hard imaging one, and it is the part a generic decoder struggles with: finding and reading a 2D symbol that is small, curved, glared or photographed at an angle. The parsing job is a different kind of problem — positional, with nested length counters — and it belongs in a parser that you can read, test against known payloads and reuse. bcbp.js is that parser: one dependency-free file that the generator encodes with and the scanner decodes with, so the two cannot drift apart. That also keeps the parser testable in isolation. It is checked against the official Resolution 792 example payloads, which is a test you can run without a camera or a browser. ## Step 4: Read the mandatory section The fixed part is 58 characters plus a 2-character size field. Because the widths are fixed, reading it is a sequence of slices: Then each leg reads its 35 characters in order. Most fields only need trimming, but the seat, the flight number and the check-in sequence are stored padded for the scanner’s benefit, not for display: 018A reads back as 18A , 0025 as 25 , 0834 as 834 . Displaying the padded form is a common way to make a scanner look wrong when it is in fact right. ## Step 5: Follow the nested size fields This is the core of the parser. A BCBP variable field is not terminated by a delimiter; it is measured by the field in front of it, three counters deep: Three details carry most of the weight here: - The unique block appears only on the first leg. It is preceded by > and the version digit, so the check for body.charAt(0) === '>' is also what tells you which layout you are reading. - A later leg starts straight at the item 17 size field. It has no version marker and no unique block, so its variable field is item 17 hex + repeated data + item 4 . - Whatever is left after the repeated block is item 4 , the carrier’s own data. It is free-form and should be preserved rather than discarded — the round trip depends on it. A pre-2008 payload has item 6 = 00 and no variable field at all — not even the item 17 size field. Treating that as “a zero-length block” is right; treating it as “then read the item 17 size field” is not. Keeping the raw content visible makes the result auditable rather than merely plausible: ## Step 6: Decode the conditional items Once you have the two blocks as substrings, each item is a fixed-width slice, and the code lists turn the single-character values into something readable: Two of these deserve a second look, because both are counter-intuitive: The baggage tag is structured, not an opaque number. Thirteen digits: a 10-digit licence plate followed by a 3-digit count of consecutive bags. The plate itself starts with a leading zero, then the carrier’s three-digit numeric code: So 0014123456002 is Air Canada (numeric code 014 ) with 2 bags — which is more useful to display than the raw digits. The date of issue stores only the last digit of the year. Item 22 is four characters: one digit of year plus a Julian day. 6261 means “year ending in 6, day 261” — which could be 2006, 2016 or 2026. Resolving it against the reference year used for the flight date is the only reading that works: Hard-coding 2000 + digit is the obvious shortcut, and it is wrong: it reports a pass issued in 2026 as 2006. Resolving against the reference year fixes that — and it also makes the official example correct. Its issue date is 1325 , a year ending in 1: Reference year | Resolved issue date | 2026 (today) | 2021-11-21 | 2012 | 2011-11-21, the date the example was actually issued | ## Step 7: Report structural checks, not just fields Fields alone do not tell you whether a payload is well formed. Nine checks do, and each one comes with its evidence so a disagreement is actionable: The length check is computed from the payload’s own declarations rather than from the actual length, which is what makes it a check at all: This matters for real-world data, because not every boarding pass in the wild is conformant. A payload can declare four legs and carry three, declare a 103-byte block and provide 90, or omit the version marker while still carrying conditional data. The checks surface those instead of letting the UI present a half-parsed pass as if it were clean. ## Step 8: Verify the security section’s signature (items 25–30) Parsing and checking length say the payload is well formed; they say nothing about whether the bytes were edited after issue. A payload can end with a security section — ^ (item 25), one character of security data type (item 28), two hexadecimal characters of byte length (item 29), then the data itself — and the companion generator writes one automatically with ECDSA P-256. A reader needs only the public half of the key pair. verifySecurityData() imports that key once (SPKI format), strips items 25–30 with the same securityBase() helper the generator signed with, and hands the remaining bytes to WebCrypto. A value that is not even base64 fails before any key is involved: Verification is asynchronous, so the signature box renders first with Verifying… and fills in when the promise resolves. The five states map onto three colours: - ok — green: the signature matches the bytes that remain after stripping. - bad — red: present but does not verify — the payload was edited after signing, signed with a different key, truncated so item 29’s declared length disagrees with the data, or not base64. - none — neutral: items 25–30 are absent. An unsigned pass is legal in BCBP, so nothing is wrong with it — unless this reader has been told otherwise. - unsupported / error — amber: WebCrypto is unavailable, or the payload did not decode, so no verdict is possible at all. Whether none is acceptable is policy, not format, so it lives in a switch rather than in the parser. Turning on Require signature re-reads whatever is already on screen — no second scan needed — and the none branch flips from an informative note to a refusal: The verdict also lands in the JSON export as signature.state and signature.accepted , so a test harness can assert on it: an unsigned pass counts as accepted only while Require signature is off. ## Common Issues and Edge Cases Aztec symbols are never detected. The enum member is BF_AZTEC . Using BF_AZTEC_CODE produces undefined , and mask |= undefined contributes nothing, so Aztec is silently excluded. Log any name the enum does not define. Cannot mix BigInt and other types when building the mask. The format enum is BigInt in 11.x. Start the accumulator at 0n . A transparent PNG of a symbol does not decode. Canvas-exported symbols have an alpha channel and a transparent pixel is (0,0,0,0) ; read as RGBA that is black, so the quiet zone fills with ink. Composite the image onto white before getImageData . The results panel re-opens dozens of times a second in camera mode. Consecutive frames see the same symbol. Add a MultiFrameResultCrossFilter with enableResultDeduplication('barcode', true) , and guard the receiver with an “already showing results” flag. Passing a Blob or a canvas to capture() returns no results. The router expects a byte buffer in the getImageData() shape — RGBA, stride = 4 × width , format: 10 . Building that object explicitly is the difference between zero barcodes and a correct decode. stopCapturing() may return undefined . It is safe to await , but not safe to chain .then() onto. Wrap it: Promise.resolve(cvRouter.stopCapturing()).then(...) . Sample chips inside the drop zone open the file picker as well as scanning. The drop zone’s own click handler fires too. Call event.stopPropagation() in the chip handler. The flight date can be out by a year. There is no year in the payload. Item 46 is a Julian day of the year, so a pass read in January for a December flight, or read five years later, can only be resolved by inference — and it will be wrong at the boundary. Report the Julian day alongside the resolved date so the ambiguity is visible. A signature that verified a moment ago turns red after editing one field. The signature covers the payload up to the end of the last leg, so changing the name, flight or seat changes those bytes and the old signature stops matching — that is the feature working, not a bug. Regenerate the pass with Re-sign in the companion generator rather than expecting a signature to survive an edit. “Item 29 declares 88 bytes but only 78 are present.” Item 29 counts the bytes of item 30, so a truncated signature fails its own length check before any key is involved. The fix is on the writer’s side: re-sign so item 29 and item 30 agree again. ## Conclusion The split matters. A barcode SDK solves the imaging problem: finding and decoding a 2D symbol on a curved, glared or poorly-lit boarding pass. The BCBP layout is a separate parsing problem, with three nested size fields and a positional item order. Keeping the two apart makes both testable, and writing the parser against the official Resolution 792 examples is what keeps it honest. Signature verification rides along in the parser rather than the SDK: the reader’s job ends at the string, and WebCrypto answers the separate question of whether the bytes were edited after issue. The companion article builds the other half of the loop: how to generate a boarding pass barcode in JavaScript , which is also where the sample images in this demo come from. ## Source Code Get the complete sample project source code on GitHub ### How to Generate a Boarding Pass Barcode in JavaScript (IATA BCBP) URL: https://www.dynamsoft.com/codepool/generate-boarding-pass-barcode-javascript.html Summary: Build a browser-side IATA BCBP boarding pass generator in JavaScript: write a Resolution 792 payload with its nested size fields, auto-sign the security section (items 25–30) with WebCrypto ECDSA P-256, render it as PDF417, Aztec Code, QR Code or Data Matrix, draw a printed or mobile pass preview on an HTML5 canvas, and print the exact field values a conformant scanner should return. Author: Xiao Ling Published: 2026-09-18 (updated 2026-09-23) Topics: Barcode, IATA BCBP, Boarding Pass, PDF417, Aztec, QR Code, JavaScript, Web, HTML5, DBRThe barcode on a boarding pass carries a payload defined by IATA Resolution 792 — an IATA Bar Coded Boarding Pass (BCBP). It is a fixed-order layout with mandatory and conditional sections, strictly sized fields, and two nested hexadecimal size fields that a reader has to follow to find where anything ends. That structure is what makes a boarding pass worth generating rather than typing text into a generic QR generator. A payload is only useful as a test case if it is well formed — correct widths, correct padding, consistent size fields — and if you know what the scanner should return, so that a wrong or missing field stands out. This article builds that generator: it composes a BCBP payload, signs the security section (items 25–30) with WebCrypto so an edited field can be caught later, renders the result as PDF417, Aztec Code, QR Code or Data Matrix on a printed or mobile pass preview, and prints the field-by-field result a conformant scanner should return. What you’ll build: a browser-side BCBP generator — the Resolution 792 encoder, the nested size fields, one-to-four flight legs, four symbologies, a security section that re-signs itself whenever a field changes, a canvas pass preview that marks what Randomise changed, and a self-check that parses the page’s own output. ## Online demo https://www.dynamsoft.com/codepool/demos/boarding-pass-generator/ ## Demo Video ## Key Takeaways - BCBP is a fixed layout, not a key-value format. There are no field tags. Items are written in a fixed order inside a block, and only trailing optional items may be omitted. - item 6 is the byte count of everything that follows it in that leg’s variable field. It is the two hex digits after each leg’s fixed block, and it counts the two nested size fields as well as the data. Computing it from the assembled bytes is the one definition that cannot drift out of step. - Padding is part of the format. The check-in sequence is four digits plus a trailing blank ( 0025 ), and the seat is a three-digit zero-padded row plus a letter ( 018A ). A scanner expects that exact spelling. - PDF417 is the printed-pass default; Aztec, QR Code and Data Matrix only became standard for printed passes with version 7 (2018). Mobile passes have used the 2D symbologies since version 2. - The flight date has no year in it. BCBP stores a Julian day of the year ( 001 – 366 ), so the year has to be inferred from the issue date or the current date. - BCBP never verifies a signature for you — but a pass can carry one. The security section (items 25–30) holds a signature over the payload; this generator writes it automatically with WebCrypto (ECDSA P-256), and checking it is the reader’s job. A signature proves the bytes were not edited, never that a reservation exists. - Sign first, append second. Item 30 lives inside the payload it would sign, so the signature covers everything up to the end of the last leg and items 25–30 are appended afterwards — the verifier strips that same section off before checking, so both sides always compare the same bytes. - Mark what a bulk action changed. A button that rewrites a dozen fields at once needs to show which ones moved, or a value you set deliberately is indistinguishable from one that was overwritten. ## Common Developer Questions ### How do I generate a boarding pass barcode in JavaScript? Compose the IATA BCBP payload as a string, then hand that string to a barcode encoder. The payload is plain ASCII: a 23-character unique mandatory section, a 35-character block that repeats per leg, a two-character hexadecimal size field, and the leg’s variable field with two more nested size fields inside it. In the browser, bwip-js renders the string as PDF417, Aztec Code, QR Code or Data Matrix on a canvas, which you can export as a PNG. ### What is the difference between IATA BCBP and a QR code? QR Code is one of the symbologies a BCBP payload can be carried in; BCBP is the data format. Since Resolution 792 version 7, a printed pass may use Aztec Code, QR Code or Data Matrix as well as the original PDF417, and a mobile pass has used the 2D symbologies since version 2. The same payload string can be encoded in any of them, so the format and the symbology are independent choices. ### Which barcode format is used on a boarding pass? PDF417 is the format Resolution 792 originally specified and still the default on paper passes. From version 7 (2018), printed passes may also use Aztec Code, QR Code or Data Matrix . Mobile boarding passes typically carry the same payload in one of those 2D symbologies because they render more compactly on a phone screen. ### How long is a BCBP payload? The fixed part of a single-leg pass is 60 characters : 23 characters of unique mandatory section, 35 characters of per-leg mandatory data, and a 2-character hexadecimal size field. The variable field that follows adds between 0 and 255 bytes, so a complete single-leg payload is 60 characters plus whatever conditional data you include. Each further leg adds another 35-character block and its own size field. ### Why does the flight date in my payload not have a year? The standard stores a day of the year, not a date. Item 46 is a three-digit Julian day, so 261 means the 261st day — 18 September, with no year attached. A reader has to infer the year from the date of issue (item 22, which stores the last digit of the year) or from the current date. This is why a boarding pass issued at the turn of the year can be genuinely ambiguous. ### Does the generated boarding pass include a digital signature? Yes. Item 30 holds an 88-character base64 ECDSA P-256 signature over the payload — everything up to the end of the last leg — and the page re-signs it every time any field changes, using WebCrypto entirely in the browser. Editing the signature field by hand latches the value so you can build a deliberate failure case, clearing it omits items 25–30 entirely, and the Re-sign button puts a valid signature back. The companion scanner article verifies those same bytes against the public half of the key pair. ### Can I use a generated boarding pass barcode to travel? No. The pass is signed with a demo key that ships in the page source, and every other field is whatever the form was filled with — the payload carries no proof of a booking behind it. Real carriers sign on their issuing server with a key that never leaves it, verified against a public key the reader already trusts. A synthetic pass exists to test a scanner, not to board a flight. ## Prerequisites - Node.js or any static file server for local development. The page itself has no build step. - A browser with an HTML5 canvas — the symbol and the preview are both drawn client-side. - bwip-js (BWIPP compiled to JavaScript), loaded from a CDN. It is the only third-party dependency. - To read the symbols back with Dynamsoft Barcode Reader, you need a license key. A 30-day free trial license covers development and testing. ## Step 1: Lay out the BCBP field table Start by writing down the layout, because every later step depends on these widths. The unique mandatory section is 23 characters: Pos | Len | Item | Field | 1 | 1 | 1 | Format code, always M | 2 | 1 | 5 | Number of legs encoded (1–4) | 3 | 20 | 11 | Passenger name, SURNAME/GIVEN NAME , left-justified | 23 | 1 | 253 | Electronic ticket indicator, E or blank | Then a 35-character block that repeats for every leg : Pos | Len | Item | Field | 24 | 7 | 7 | Operating carrier PNR | 31 | 3 | 26 | From airport (IATA) | 34 | 3 | 38 | To airport (IATA) | 37 | 3 | 42 | Operating carrier designator | 40 | 5 | 43 | Flight number, 4 digits + optional letter | 45 | 3 | 46 | Date of flight, Julian day of year | 48 | 1 | 71 | Compartment code | 49 | 4 | 104 | Seat number, 3-digit row + letter | 53 | 5 | 107 | Check-in sequence number | 58 | 1 | 113 | Passenger status | Positions 59–60 are item 6, the size field. Encode the fixed part first, with the padding rules spelled out: The padding rules are the part that catches people out. Alphanumeric items are left-justified with trailing blanks; numeric items carry leading zeros. The seat and the sequence number look similar but pad differently: Seat 18A becomes 018A — leading zeros. Sequence 42 becomes 0042 — leading zeros and a trailing blank. The official Resolution 792 examples spell it that way ( 0025 , 0027 ), and a scanner has to cope with that exact spelling, so the generator reproduces it rather than choosing the tidier-looking right-aligned form. ## Step 2: Pack the conditional sections in fixed order The variable field holds three things, one after another: the once-per-pass data, the once-per-leg data, and the carrier’s own space. Both conditional blocks are a fixed sequence of slots with known widths, which is what lets a reader parse them without tags: The complete once-per-pass block (item 10): Item | Len | Field | 15 | 1 | Passenger description | 12 | 1 | Source of check-in | 14 | 1 | Source of issuance | 22 | 4 | Date of issue — last digit of the year plus the Julian day | 16 | 1 | Document type | 21 | 3 | Airline designator of the issuer | 23 | 13 | Baggage tag; up to three, so up to 39 characters | 31 | 13 | Non-consecutive baggage tag | 32 | 13 | Second non-consecutive baggage tag | And the once-per-leg block (item 17): Item | Len | Field | 142 | 3 | Airline numeric code | 143 | 10 | Document form / serial number | 18 | 1 | Selectee indicator | 108 | 1 | International documentation verification | 19 | 3 | Marketing carrier designator | 20 | 3 | Frequent flyer airline | 236 | 16 | Frequent flyer number | 89 | 1 | ID / AD indicator | 118 | 3 | Free baggage allowance | 254 | 1 | Fast track | Packing then means concatenating slots until the last non-empty one, and dropping only the trailing empties: Because the block is positional, a field can only be present if every field before it is present too. One consequence is worth surfacing in the UI: if a user fills in a later item and leaves an earlier one blank, that blank still gets packed, with its own padding character — data the user never entered. Writing a frequent flyer number therefore forces the free baggage allowance in front of it to appear as blanks. The validator looks for that gap and reports it instead of silently inventing the filler: One block remains at the very end of the variable field: the security section, items 25–30. It is not typed into the form — it is signed — and Step 8 covers it. ## Step 3: Write the size fields This is the step that breaks generated passes. The variable field is not self-delimiting; it is measured by the field in front of it, and it contains two smaller size fields of its own. Writing it is easiest if you assemble the bytes first and then take their length: Reading the assembled block back makes the arithmetic self-evident: - > plus the version digit — 2 bytes (items 8 and 9) - the item 10 size field — 2 bytes - the unique conditional data - the item 17 size field — 2 bytes - the repeated conditional data - the airline’s own data (item 4), which is whatever remains For the official single-leg example with no conditional data, that gives item 6 = 06 : A later leg has no unique block, so its size field is just the repeated size plus the carrier data: The page shows the assembled payload so you can count the bytes yourself: ## Step 4: Support more than one leg The mandatory block repeats per leg, but the 23-character header does not — the passenger name is written once. The PNR, however, sits inside the repeating block, so a two-leg pass can carry a different locator on each leg. The official Resolution 792 two-leg example does exactly that: So the record keeps the PNR per leg, and the form propagates an edit to every leg that is still carrying the previous value: One thing to watch: the free baggage allowance (item 118) is also per leg, so a second leg with no allowance omits it — while the PNR, in the same block, still appears. A two-leg pass is a good test of your size fields, because there are three of them to get wrong instead of one. ## Step 5: Render the symbol with bwip-js The payload is a plain string, so rendering is the easy part. Map each symbology to its BWIPP encoder name and a module size: minVersion is not cosmetic. Aztec Code, QR Code and Data Matrix were only added to the standard for printed passes in version 7 , so picking one of them silently sets the version field to 7. A payload that claims version 6 while travelling in a QR Code claims a combination the standard did not allow. Also worth knowing: a symbol exported from a canvas is transparent by default. toCanvas leaves the background unset, so a PNG saved straight from it carries an alpha channel. Handed those pixels as RGBA, a reader treats (0,0,0,0) as black, which floods the quiet zone with ink and hides the symbol. Fill the canvas white first, or pass backgroundcolor: 'FFFFFF' to the encoder. ## Step 6: Draw a pass preview A preview that looks like a boarding pass is easier to sanity-check than a bare symbol: you can see at a glance that the name, route and seat are the ones you typed. The drawing is ordinary Canvas 2D; the parts worth calling out are the watermark and the symbol panel: The symbol is drawn into a tinted panel and scaled to fit, which keeps it away from the pass border — the same quiet-zone reasoning as paddingwidth above: The same payload also renders as a mobile wallet pass, which is the layout a phone would show: ### Marking what Randomise changed A button that rewrites a dozen controls at once is disorienting: nothing tells you which values moved, so a field you had set deliberately looks the same as one that was overwritten. Snapshotting the form before the rewrite and comparing after fixes that in a few lines: Two details are worth keeping: - The reflow. Removing and re-adding the class in the same frame does not restart a CSS animation — the browser coalesces the two mutations. Reading offsetWidth between them forces a style recalculation, which is the cheapest way to make the animation replay on every click. - The reduced-motion fallback. Skipping the animation entirely would remove the information, not just the motion, so the media query keeps a static colour instead: The count of changed controls is worth reporting too — it turns “did that do anything?” into a number: ## Step 7: Prove the payload by parsing it back Testing a scanner needs a generator you can verify. The most direct check is to parse your own output with the same code the scanner will use: write the decoder alongside the encoder, and treat the parse result as the test oracle rather than restating the form. Because the two directions share one field table, the table above is read back from the bytes. That also makes a round-trip test possible: parse a payload, rebuild the record, re-encode, and require the bytes to come back identical. Running that against the official Resolution 792 examples is what turns “it looks right” into a check. On page load the demo logs: The four vectors cover the awkward cases rather than the happy path: a single leg with no conditional data (where item 6 is 00 and nothing follows it — not even the item 17 size field), a single leg with unique, repeated and security data, a two-leg pass with a different PNR per leg, and a version 6 pass whose size fields are present but zero. The structural checks report the same thing to the user: ## Step 8: Sign the security section automatically The final block of the variable field is the security section — items 25–30, written once after the last leg. ^ marks the beginning (item 25), one character carries the type of security data (item 28), two hexadecimal characters carry the byte length of item 30 (item 29), and everything after that is the data itself: Signing it raises one structural problem: item 30 is inside the payload it would sign , and a signature cannot cover itself. The fix is to sign everything up to the end of the last leg, then append items 25–30 afterwards — and for the verifier to strip that same section off before checking, so both sides always compare the same bytes. One helper does the trimming for both directions: The second problem is encoding. ECDSA P-256 returns a raw 64-byte r‖s signature; hex-encoded that is 128 characters, and validate() puts a 100-character ceiling on item 30 — a hex signature is rejected before any key is involved. Base64 of the same bytes is 88 characters, comfortably inside the limit, so that is what item 30 carries. The signing itself is WebCrypto: generate() then signs on every pass: encode the record with security: null , sign those bytes with the demo private key, and write the result back into the two security fields: The demo private key ships with the page, which is the one thing a production issuer must never do: that key belongs on the issuing server, only the signature travels, and readers get the public half — exactly what the companion scanner verifies against. WebCrypto also needs a secure context, so the page must be served from http://localhost or https ; when it is not, the pass is left unsigned as typed and the hint under the field says so. Because signing runs on every change, a keystroke in either security field would be overwritten immediately — so that keystroke latches manual mode instead: the value stays exactly as typed and nothing re-signs until Re-sign or Randomise is pressed. After each render the page verifies its own output against the public key and reports the verdict in the hint: green for a signature that matches, red for one that does not (calling out the hand edit), plain when items 25–30 are absent. Re-signing without changing anything still produces a different value — ECDSA draws a fresh random nonce for every signature — but verification always strips back to the same base, so every one of those signatures checks out. ## Common Issues and Edge Cases The payload is two bytes shorter than the scanner expects. item 6 must count the two nested size fields as well as the data. The trap is computing it as “unique length + repeated length” and forgetting that '>' + version and the two 2-character size fields are inside the block too. Assemble the bytes first and take their length. item 6 = 00 but data follows. A pre-2008 pass has no version marker and no variable field at all. If you write 00 and then append conditional data, you have produced a contradictory payload. Either write a version or write no conditional data. The check-in sequence does not round trip. 42 encodes as 0042 , and reading it back gives 42 again — but if you pad it as ` 042` a scanner that compares raw strings will disagree with you. Match the examples: leading zeros, trailing blank. A name without a slash. The passenger name is SURNAME/GIVEN NAME ; item 11 is 20 characters wide and left-justified. A name with no slash is not a BCBP name, so the generator rejects it rather than guessing where the split goes. A transparent PNG of the symbol will not scan. Covered in Step 5, but it is a common “the generator is broken” report that turns out to be the export. Fill the background white. More than four legs. The standard allows at most four, even though the leg count field could hold more. Optional fields out of order. Because the blocks are positional, “item 9 present, item 4 absent” is not expressible. The validator says so rather than silently emitting filler. Item 30 is refused as too long. validate() caps item 30 at 100 characters. A P-256 signature hex-encoded is 128 and is rejected before anything is verified; base64 of the same 64 raw bytes is 88 characters, which is why that is what the generator writes. Change the signature algorithm and this ceiling is the first thing to re-check. The signature changes even when nothing else did. That is ECDSA being randomized: every signature draws a fresh nonce, so signing identical bytes again produces a different — equally valid — value. Verification strips items 25–30 first, so any signature over that same base still checks out; only an edit to the payload before ^ invalidates one. ## Conclusion Building a BCBP generator is mostly a formatting exercise, with one piece of real arithmetic: the nested size fields. If the widths, the padding and all three size fields are right, a scanner reads back every field; if any of them is wrong, it returns a partial or misread set, or a length check reports a mismatch. Writing the decoder alongside the encoder is what makes the result checkable, and running that decoder against the official Resolution 792 examples — re-encoding them and comparing bytes — is what confirms it. The security section then adds the one piece of cryptography on top: sign what you wrote, and any field edited afterwards fails to verify. The companion article covers the other half of the loop: how to read a boarding pass barcode in JavaScript with Dynamsoft Barcode Reader and the same parser. ## Source Code Get the complete sample project source code on GitHub ### How to Generate GS1 Barcodes in JavaScript for Scanner Testing URL: https://www.dynamsoft.com/codepool/generate-gs1-barcode-javascript.html Summary: Build a browser-side GS1 barcode generator in JavaScript: compose a validated GS1 element string from application identifiers, calculate GTIN and SSCC check digits, pick the symbology a real supply chain would use, render a test label on an HTML5 canvas, and export the result together with the exact parse a conformant scanner should return. Author: Xiao Ling Published: 2026-09-16 (updated 2026-10-20) Topics: Barcode, GS1, GS1 AI, DataBar, JavaScript, Web, HTML5, Data Matrix, DBRYou have written a GS1 parser, and now you need something to test it with. A real product label is the wrong answer twice over: you probably do not have the stock, and somebody else’s batch and serial numbers are not yours to put in a test fixture anyway. So you go looking for a generator, and find plenty of them — except they encode text . Type a GTIN, get a DataBar. Type (01)09506000135000(17)270430(10)LOT-42 , the way GS1 actually writes it, and they either print those characters literally into the symbol or refuse outright. A reader can decode that image perfectly and still return nothing useful, because the image was never a GS1 element string to begin with. A GS1 generator has to work the other way round. The list of application identifiers is the source of truth ; the element string, the FNC1 positions, the check digits and the symbology choice are all derived from it. Once that is the design, a second thing becomes possible: the generator can print the exact parse a conformant scanner should return, so a failing test tells you which side is wrong — the symbol or the parser. What you’ll build: a browser-side GS1 generator that composes a validated element string from application identifiers, calculates GTIN/SSCC check digits, recommends the symbology a real supply chain would use, renders a test label on an HTML5 canvas, and exports the PNG together with the table of values a scanner should report. Online demo ## Key Takeaways - Encoding for GS1 is a payload problem, not a symbology problem: get the element string right and the encoder handles the FNC1 placement for you. - The AI table does three jobs — validation, sample generation and the length rules — so it belongs in one place. - Check digits are calculated, never typed . A GTIN whose check digit is wrong is a fine test of the failure path and a useless test of everything else. - Not every symbology can carry every payload: DataBar, ITF-14 and EAN-13 encode the GTIN and nothing else , and GS1 constrains which AIs may travel together. - A long payload must be re-encoded at a smaller module size, never scaled down . A blurred linear symbol tests your camera, not your parser. - Generating the expected parse alongside the image turns each PNG into a test case instead of a picture. ## Common Developer Questions ### How do I generate a GS1 barcode in JavaScript? Compose the element string by concatenating each AI with its data, then hand that string to an encoder that understands GS1 syntax. The bwip-js library (a JavaScript port of BWIPP) accepts the human-readable (01)…(10)… form for its GS1 symbologies — gs1datamatrix , gs1qrcode , gs1_128 , databarexpanded , databaromni — and inserts the FNC1 bytes itself. ### Which barcode symbology should a GS1 payload use? It is decided by the payload, not by preference. A GTIN alone belongs in GS1 DataBar Omnidirectional (or EAN-13 for a GTIN-13). A GTIN plus batch, date or serial needs a symbology that can carry more than the GTIN: DataBar Expanded, GS1 DataMatrix, GS1 QR Code or GS1-128. An SSCC has no GTIN at all, so GS1-128 is the usual carrier. ### How do I calculate a GTIN check digit in JavaScript? Weight the digits alternately by 3 and 1 starting from the rightmost data digit, sum them, and take (10 - sum % 10) % 10 . The same mod-10 routine covers GTIN-8/12/13/14, SSCC, GLN and GSRN. ## Step 1: Make the AI Table the Model Everything else is derived from this table, so it is worth getting right first. Each entry needs four things: the code, a name, a length rule, and a way to produce a valid sample. The fixed / max distinction is not metadata — it is what tells the encoder whether a separator is needed after this element, and it is what lets a parser recover a payload whose separators were stripped. The sample() function earns its place too. Every AI in the table can produce a value that passes its own validation, so “Randomize data” is always available and a half-built payload is never blocked on typing a plausible SSCC by hand. One detail that matters more than it sounds: when Randomize data replaces the values, the fields that changed are marked for a moment . Random sample values are all digit soup — 00950600403582 and 00950600786614 look equally arbitrary — so without the marker a click reads as “nothing happened”, which is exactly the bug report this page got. The marker is a CSS animation on the row that fades out on its own and is removed from the DOM after 1.4 s, and it respects prefers-reduced-motion by dropping the animation while keeping the colour change, because the colour is the information. ## Step 2: Calculate Check Digits, Don’t Ask for Them One routine covers GTIN, SSCC, GLN and GSRN, because they all use the same mod-10 scheme. Completing the digit automatically is what makes a generated image a fair test: a scanner that verifies check digits would correctly reject a hand-typed GTIN, and you would spend the afternoon debugging the scanner. ## Step 3: Let the Payload Pick the Symbology Twelve symbologies can carry GS1 data, and they are not interchangeable: Symbology | Kind | What it can carry | GS1 DataBar Omnidirectional | 1D | GTIN, full-height retail symbol | GS1 DataBar Truncated | 1D | GTIN, shorter bars for small packaging | GS1 DataBar Stacked / Stacked Omnidirectional | 1D | GTIN, split across two rows | GS1 DataBar Limited | 1D | GTIN starting with 0 or 1, smallest DataBar | GS1 DataBar Expanded / Expanded Stacked | 1D | GTIN plus up to 74 more characters | GS1 DataMatrix | 2D | Any element string | GS1 QR Code | 2D | Any element string, consumer readable | GS1-128 | 1D | Any element string, logistics default | ITF-14 | 1D | GTIN-14 only | EAN-13 | 1D | GTIN-13 only | The recommendation is a small decision function over the payload’s AIs, and it is worth having because it encodes the field’s own habits: Validation is then relative to the chosen symbol, which is the only way it can be meaningful: a GTIN plus a batch is perfectly encodable in DataBar Expanded and completely unencodable in DataBar Omnidirectional. And every message that diagnoses a problem carries the change that resolves it. “A DataBar, ITF-14 or EAN-13 symbol carries the GTIN and nothing else” is followed by a Switch to GS1 DataMatrix button; a wrong check digit offers the corrected digit; a serial number with no trade item offers Add AI 01 ; a price in a currency with no quantity offers Add AI 30 . That is not politeness, it is the difference between a working tool and a puzzle. The GS1 length rules, the mod-10 check digit and the AI pairing constraints are specialist knowledge, and the people most likely to hit these errors are exactly the ones who do not have it yet. A message that only diagnoses leaves them to guess; a message with the remedy beside it teaches the rule and unblocks the payload at the same time. The payload model carries the remedies as data, so the UI never has to guess: The pairing rules are worth stating outright, because the encoder’s own message (“One of more requisite AIs for AI (21) are missing: 01 OR 03 OR 8006”) arrives too late to be actionable: AI | needs | why | 21 serial number | 01 , 03 or 8006 | a serial identifies a unit, so it needs the item it belongs to | 393x price in a currency | 30 , or a 31nn / 32nn / 35nn / 36nn measure | a unit price needs the quantity it is a price of | ## Step 4: Feed the Encoder the AI Syntax bwip-js is the encoder, and its GS1 symbologies accept the bracketed notation directly — the same string GS1 prints under a symbol as the human readable interpretation: BWIPP works out where the FNC1 bytes belong from the AI table: after 10 , which has no fixed length, and not after 17 , which does. That is a great deal of correctness to get for free, and it is the reason the payload model submits to the encoder as an AI list rather than as a hand-built byte string. Two symbologies do not take AI syntax, and getting them wrong produces a silently different product: That ITF-14 comment is a bug I shipped and then found. Passing 13 digits to an ITF-14 encoder looks reasonable and is wrong: the encoder appends a check digit, so a GTIN that already ended in one gets a second one computed over it. The generated label decoded cleanly to the wrong number, which is the worst kind of test fixture — it fails a scanner that is working perfectly. ## Step 5: Render a Label a Camera Can Actually Read A symbol floating on a white rectangle is not what a camera sees. Draw the thing that gets scanned: brand, product name, the identifiers in human-readable form, the symbol, and the HRI beneath it. The layout detail that matters is the symbol band: it spans the full label width, because a logistic GS1-128 with five data elements is a lot of bars and squeezing it into a narrow column is how a test label ends up undecodable. The size detail matters more. When a symbol is too wide for its frame, re-encode it at a smaller whole-number module size; do not scale the finished image : Scaling a linear symbol by a fraction blurs the module edges, and a symbol whose modules are no longer resolvable cannot be decoded however good the scanner is. Keeping the module size an integer number of pixels keeps every bar edge crisp. When even one pixel per module overflows the frame, the honest thing is to say so rather than hand out a weak image: For a decoder test, the same page exports the bare symbol with its quiet zone and no label furniture at all. ## Step 6: Print the Expected Result This is the part that turns a picture into a test. For the payload that is on screen, the page states: - the element string a decoder should return, with | marking each position where an FNC1 byte has to appear; - the human readable interpretation ; - every application identifier with the value the scanner should report, including the check-digit verdict; - and the GS1 Digital Link . A | only appears where a variable-length element needs terminating. Drawing one after every element would be easier to read and wrong: a fixed-length element needs no terminator, and showing one invites the reader to think it does. ### The preview is only as current as the last successful generation There is a failure mode here that is easy to ship and hard to notice: the preview and the expected-result table are produced after validation passes, so a payload with errors simply never reaches them — and whatever was drawn last stays on screen, looking current. That is worse than a blank canvas, because it invites someone to download or copy values that do not describe the payload in front of them. So when the payload has errors, everything downstream of generation is explicitly marked out of date in one place: The tabs deserve their own note. They used to look broken: the pressed state moved, but the early return above skipped both redraws, so clicking Symbol only changed nothing visible. A control that appears to respond and does not is worse than one that says it is unavailable, so they are disabled with a reason attached — and one click on the fix re-enables them, redraws the preview and restores the oracle together. ## Step 7: Close the Loop The generator is only worth having if the images actually round-trip. The verification harness drives both pages the way a person would: it renders the label in the generator, reads the PNG out of the canvas, uploads it to the GS1 scanner through the scanner’s own file input, and diffs every application identifier. Eleven scenarios, eleven matches, twice in a row with freshly randomised payloads — including the cases that only a real decoder can teach you: an ITF-14 that had been given a second check digit, a DataBar whose GTIN arrives with no AI, and a DataBar Expanded whose FNC1 separators the decoder dropped, letting the batch number swallow the serial that followed it. The dual-marked retail pack used in the last scenario is the subject of the GS1 2D retail POS readiness checklist : which carrier a POS should trust, which GTIN it should emit, and how to keep a pack with two symbols from ringing up twice. ## Scope and Limitations - GS1 Composite is not offered. bwip-js has no composite encoder, and a composite is anyway two symbols a reader has to associate. - DataBar Limited, ITF-14 and EAN-13 encode the GTIN and nothing else. The page reports the extra elements as an error rather than dropping them, and offers the symbology that can carry them. - A generated image is a fair test of decoding and parsing, and no test of authenticity. The payload is plaintext, so a parseable symbol proves only that it is well formed. Digitally signed carriers — an mDL, or the encrypted PDF417 on a South African driving licence — are the formats where a successful read says something about origin, and those cannot be generated from a web page at all. - Sample data only. Every value is synthetic and the preview is stamped SAMPLE . A GS1 barcode is not a secret and not an authority. ## Source Code Get the complete sample project source code on GitHub To read the labels back, open the GS1 barcode scanner demo — no install required — or build the same reader yourself with the GS1 barcode scanner tutorial , which splits the element string with the AI table this generator writes into every label. ### How to Build an Expo Barcode Scanner for Android and iOS URL: https://www.dynamsoft.com/codepool/expo-barcode-scanner.html Summary: A step-by-step tutorial for building an Expo (React Native) barcode scanner app that decodes 1D and 2D barcodes with the Dynamsoft Capture Vision native SDK through a hand-written Expo module — live camera scanning, photo-picker scanning, and result overlays with corner points. Author: Xiao Ling Published: 2026-09-04 (updated 2026-11-05) Topics: Barcode Reader, QR Code, Barcode Scanner, Expo, React Native, TypeScript, Kotlin, Swift, Android, iOSScanning barcodes in an Expo app usually means installing a React Native plugin that wraps some native decoder. This sample takes a different route: the native bridge is written by hand inside the app as a local Expo module, so the app talks directly to the Dynamsoft Capture Vision native SDK on Android and iOS — no third-party scanning plugin in between. What you’ll build: An Expo SDK 57 app ( expo-barcode-scanner ) with a full-screen native camera scanner that decodes QR codes and other 1D/2D barcodes with the Dynamsoft Capture Vision template ReadBarcodes_Default , draws live overlays around every detected barcode, and returns a results list containing the decoded text, the barcode format, and the four corner points. A system photo-picker path decodes barcodes from existing images, and a scanFile method decodes from a local file path. ## Demo Video: Expo Barcode Scanner in Action ## Key Takeaways - You can call Dynamsoft’s native mobile SDKs from Expo without a third-party plugin: implement a local Expo module (Kotlin on Android, Swift on iOS) under the app’s modules/ folder and expose it to TypeScript with requireNativeModule . - The ReadBarcodes_Default template reads all supported 1D and 2D formats from live camera frames with no per-format configuration, and each decoded item comes with text, formatString , and a four-point location for drawing overlays. - Because activity results cannot be observed from an Expo module on Android, the module launches an invisible bridge activity that hosts startActivityForResult and settles the promise — a pattern that keeps the bridge promise-based and cancel-aware. - Camera, photo-picker, and file scanning share one native engine and one result type, so the React Native UI stays identical regardless of the image source. ## Common Developer Questions ### How do I decode barcodes in an Expo app with the Dynamsoft native SDK? Add a local Expo module that wraps the SDK and call three methods from JavaScript: initLicense() , then startScan() for the live camera scanner or scanFromGallery() / scanFile() for still images. The sample module is named ExpoDynamsoftBarcodeScanner and is implemented in ExpoDynamsoftBarcodeScannerModule.kt and .swift . ### What formats does the scanner support? The Dynamsoft Capture Vision ReadBarcodes_Default template covers 1D formats (Code 39, Code 128, Code 93, Codabar, EAN-13, EAN-8, ITF, UPC-A, UPC-E, and more) and 2D formats (QR Code, Data Matrix, PDF417, Aztec, and Micro QR), all in one scan session with no template tuning. ### What does each scan result contain? Each item in the resolved results array contains text (the decoded payload), formatString (for example QR_CODE or CODE_128 ), and points — four {x, y} corner locations of the barcode in the scanned frame. The React Native UI renders them as a list, and the native scanner draws matching overlays on the live preview. ### Can the same native code handle a photo-picker image? Yes. scanFromGallery() opens the system photo picker and decodes the selected image on the native side with the same engine and template; scanFile({ uri }) does the same for a path or content URI the app already holds. Both resolve with the identical ScanResult shape. ## Prerequisites Before you start, make sure you have the following: - Node.js (LTS) and npm for the Expo toolchain - Android Studio (latest) with JDK 17 and a connected Android device or emulator - Xcode (latest, macOS only) with a connected iPhone and a signing team configured in Xcode → Settings → Accounts - A Dynamsoft license key — the sample embeds a time-limited trial key that requires a network connection on first use Get a 30-day free trial license at dynamsoft.com/customer/license/trialLicense ## How the Sample Project Is Organized The complete app lives in the examples/expo-barcode-scanner folder of the sample repository: ## Step 1: Scaffold the Expo App and the Local Module Create the project with the blank TypeScript template and scaffold the module: If the scaffolder creates the module under modules/modules/ , move it up one level and delete the empty wrapper. Restrict expo-module.config.json to the native platforms and align the module class names: ## Step 2: Add Camera and Photo Library Permissions Declare the usage descriptions in app.json ; the Android module manifest adds the CAMERA and photo-library permissions that are merged into the app manifest: ## Step 3: Define the TypeScript API and the Result List UI The module surface declares the bridge methods and the result type. The location of every decoded barcode is delivered as four corner points: The home screen in App.tsx offers a Camera / Image File toggle, runs the same license-and-scan flow for both sources, and renders each decoded barcode as a card with its format, text, and corners: ## Step 4: Implement the Android Native Module The Android module adds the self-contained Dynamsoft Capture Vision bundle and appcompat (the scanner activity needs a LifecycleOwner for the camera): ScannerEngine.kt owns a single CaptureVisionRouter shared by the camera and file sources. The barcode preset template is used for both: ScannerActivity.kt is the full-screen scanner. A CapturedResultReceiver receives every decoded frame, enables the Confirm button as soon as at least one barcode is found, and draws the result quads on the DBR drawing layer of the camera view: Confirming serializes the items ( text , formatString , points ) to a JSON array and returns it as the activity result. As in the MRZ sample, BridgeResultActivity hosts the startActivityForResult call on behalf of the module and resolves the parked promise with the parsed JSON; a cancel produces a canceled rejection. ## Step 5: Implement the iOS Native Module The podspec depends on the self-contained Dynamsoft framework (never combine it with separate core or license pods — duplicate Objective-C classes break the camera preview): ExpoDynamsoftBarcodeScannerModule.swift presents BarcodeCameraScanViewController on the main queue. The controller binds a CameraView + CameraEnhancer to a CaptureVisionRouter , loads the barcode templates shipped inside the framework, and applies the decoded items to a custom green drawing layer in its CapturedResultReceiver : For the file data source the module runs a background decode with the same template and converts each item’s location points (wrapped as NSValue ) into plain {x, y} dictionaries: ## Step 6: Build and Run the App Self-contained release builds are produced with: Aim the camera at any barcode — the preview highlights every decoded barcode and the status bar shows the running count. Tap Confirm to open the results list with format, text, and corner coordinates: ## Common Issues & Edge Cases - Black camera preview on iOS when additional Dynamsoft pods are installed: DynamsoftCaptureVisionBundle already embeds the core and license modules. Adding DynamsoftCore or DynamsoftLicense separately registers duplicate Objective-C classes at launch — remove them and re-run pod install . - The app cannot run in Expo Go: the module registers custom activities and view controllers, so use npx expo run:android / npx expo run:ios or a release build. - “No barcodes were found in the image” on file scans: the image needs a complete, in-focus barcode. Damaged labels or extreme skew can fail; retry with a sharper capture. On the live camera, the Confirm button only enables after the first decode. - Cancel behavior: pressing back or Cancel rejects the promise with canceled ( RESULT_CANCELED on Android). The sample filters that message with /cancel/i instead of surfacing an error. - Trial license expires or the device is offline: the embedded key is time-limited and validates against Dynamsoft’s license server. Replace it in License.kt (Android) and in Constants.licenseKey of the Swift module before shipping. - Module name mismatches: requireNativeModule('ExpoDynamsoftBarcodeScanner') must match the class names and expo-module.config.json entries ( ExpoDynamsoftBarcodeScannerModule on both platforms); otherwise autolinking registers nothing and the import throws at startup. ## Source Code Get the complete sample project source code on GitHub The native bridge sources live in the modules/expo-dynamsoft-barcode-scanner folder of that project. For more on the underlying SDK, see the Dynamsoft Capture Vision documentation . ### How to Build an Ionic Vue QR Code Scanner with the Dynamsoft Capture Vision Native SDK URL: https://www.dynamsoft.com/codepool/ionic-vue-qr-code-scanner.html Summary: Build a cross-platform Ionic Vue QR code and barcode scanner powered by the Dynamsoft Capture Vision native SDK (capturevisionbundle 3.6.4000) on Android and iOS. Two data sources, no JavaScript SDK, real-time native overlay. Author: Xiao Ling Published: 2026-09-03 (updated 2026-10-27) Topics: Ionic, Capacitor, Android, iOS, QR Code, Barcode, Capture Vision, Native SDK, DataMatrix, PDF417Decoding QR codes and 1D barcodes from a phone camera needs a production-grade native pipeline. With the Dynamsoft Capture Vision native SDK ( com.dynamsoft:capturevisionbundle:3.6.4000 on Android, DynamsoftCaptureVisionBundle 3.6.4000 on iOS) wrapped in a small in-app Capacitor plugin, every frame is processed on-device with the multi-format preset template and the result is returned as JSON. This article walks through the ionic-vue-qr-code-scanner reference project — one Ionic Vue app, one in-app plugin, two data sources, and zero JavaScript scanning SDK. The scanner supports QR Code, DataMatrix, PDF417, Aztec, Code 39/93/128, EAN, UPC, ITF and Codabar, with real-time contour drawing on the native preview. The same code path accepts a still image from the gallery so a user can pick a saved photo and decode it with the same multi-format pipeline. ## What you’ll build - An Ionic Vue app that exposes two clearly separated data sources — Camera and File — with the live preview running entirely on the native side. - A multi-format barcode scanner that runs the built-in barcode preset template ( ReadBarcodes on Android, ReadBarcodes_Default after loading the SDK templates on iOS) on every camera frame and overlays the decoded contour through Dynamsoft’s DrawingLayer system on both platforms ( DBR_LAYER_ID on Android, a custom green-styled layer on iOS). - An in-app Capacitor plugin ( BarcodeScannerNative ) that returns every decoded barcode with text, format, format string and four corner points, ready to be rendered as a list. - A matching iOS Swift implementation that drops into the same Xcode project once the Dynamsoft pods are installed via pod install (see Step 4). ## Key Takeaways - Native SDK end-to-end. All decoding happens on-device. The WebView only renders the result; it never loads a JavaScript scanner. - Camera + file, one engine. Both data sources feed the same CaptureVisionRouter through the same ScannerEngine singleton so the deep-learning models load only once. - Latest Capture Vision release. Both platforms use the same 3.6.4000 SDK ( com.dynamsoft:capturevisionbundle and DynamsoftCaptureVisionBundle ). - No third-party plugin. The Capacitor bridge is fully implemented in this project. ## Architecture ## Common Developer Questions ### What barcode formats are supported? QR Code, DataMatrix, PDF417, Aztec, Code 39, Code 93, Code 128, EAN-8, EAN-13, UPC-A, UPC-E, ITF and Codabar. The ReadBarcodes preset template enables the entire set out of the box — no extra configuration is required. ### Should I add @capacitor/camera to handle the gallery picker? No. The native plugin implements its own gallery picker on Android (an ACTION_PICK intent through MediaStore ) and on iOS ( UIImagePickerController after requesting photo-library access). Adding @capacitor/camera would introduce a second picker that the user has to authorise separately. The reference project keeps the picker inside the plugin for exactly this reason. ### Why does the camera page not show an HTML video tag? DSCameraView (iOS) and CameraView (Android) are native views from the Camera Enhancer module. They run AVFoundation and CameraX respectively, which gives the scanner access to frame-accurate control and the drawing layer for real-time contour rendering. An HTML