zpl_render 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +49 -0
- data/LICENSE.txt +21 -0
- data/README.md +145 -0
- data/exe/zpl_render +62 -0
- data/lib/zpl_render/barcode/code128.rb +332 -0
- data/lib/zpl_render/barcode/code39.rb +53 -0
- data/lib/zpl_render/barcode/interleaved2of5.rb +42 -0
- data/lib/zpl_render/barcode/pdf417.rb +201 -0
- data/lib/zpl_render/barcode/pdf417_tables.rb +354 -0
- data/lib/zpl_render/barcode/qr.rb +50 -0
- data/lib/zpl_render/canvas.rb +112 -0
- data/lib/zpl_render/font.rb +210 -0
- data/lib/zpl_render/font_data.rb +153 -0
- data/lib/zpl_render/fonts/LICENSE-LiberationSans.txt +102 -0
- data/lib/zpl_render/fonts/LiberationMono-Regular.ttf +0 -0
- data/lib/zpl_render/fonts/LiberationSans-Bold.ttf +0 -0
- data/lib/zpl_render/graphic_field.rb +112 -0
- data/lib/zpl_render/helvetica_metrics.rb +17 -0
- data/lib/zpl_render/output/pdf.rb +39 -0
- data/lib/zpl_render/output/png.rb +35 -0
- data/lib/zpl_render/parser.rb +90 -0
- data/lib/zpl_render/renderer.rb +627 -0
- data/lib/zpl_render/truetype.rb +428 -0
- data/lib/zpl_render/version.rb +5 -0
- data/lib/zpl_render.rb +71 -0
- metadata +127 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 05e06eca743b13623cd089ca67956463df7ddeccba669ac184028669a1df1367
|
|
4
|
+
data.tar.gz: d30efa23e8265c64b11a3586cbb547f3dfe57e526eb1dfdaa277f127d65c7942
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 8a2deff01c66b826be88bb43a2fafc457a735911b530b91b3523c349d1b85881947f46afc10807053fb8cdf3bc61c6f9df945d7798c49ef53946ea1a5183bf02
|
|
7
|
+
data.tar.gz: 0c26655758c3d6e790ad68b886e53c5a3932fe295391108bd6e6d7a7bddd5abb5140a899738e2822fbb3ab57a8f023f911f25809f917750aaa5878da9d498ada
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0] - 2026-07-31
|
|
11
|
+
|
|
12
|
+
Initial release.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- ZPL II parser and renderer producing one 1-bit dot canvas per `^XA..^XZ`
|
|
17
|
+
format, at true printer resolution (dpmm 6/8/12/24).
|
|
18
|
+
- PNG output (`ZplRender.to_png` / `.to_pngs`, chunky_png) and PDF output
|
|
19
|
+
(`ZplRender.to_pdf`, prawn) with one page per label at exact physical size.
|
|
20
|
+
- Barcodes, scanner-verified against the zxing-cpp engine in the spec suite:
|
|
21
|
+
- Code 128 (`^BC`): own ISO/IEC 15417 encoder with ZPL subset invocation
|
|
22
|
+
codes (`>0`..`>;`), modes N / A (automatic) / U (UCC case) / D (GS1),
|
|
23
|
+
mod-103 check symbol, mod-10 UCC check digit.
|
|
24
|
+
- PDF417 (`^B7`): own ISO/IEC 15438 encoder, byte + numeric compaction,
|
|
25
|
+
Reed-Solomon error correction over GF(929), security levels 0-8,
|
|
26
|
+
columns/rows/truncated.
|
|
27
|
+
- QR (`^BQ`) via rqrcode_core, with ZPL `<ECC><mode>,` field-data prefixes.
|
|
28
|
+
- Code 39 (`^B3`) with optional mod-43 check digit.
|
|
29
|
+
- Interleaved 2 of 5 (`^B2`) with optional mod-10 check digit.
|
|
30
|
+
- Text rendering through a built-in pure-Ruby TrueType rasterizer using
|
|
31
|
+
bundled Liberation Sans Bold (scalable font 0) and Liberation Mono Regular
|
|
32
|
+
(bitmap fonts A-H, with ZPL matrix cells and inter-character gaps),
|
|
33
|
+
metrics calibrated against Labelary reference renders; embedded
|
|
34
|
+
public-domain 8x8 bitmap font as fallback.
|
|
35
|
+
- Fields and graphics: `^FO ^FT ^FS ^FD ^FV ^SN`, fonts `^A ^A@ ^CF`,
|
|
36
|
+
field blocks `^FB`, hex escapes `^FH`, `^CI`, field reverse `^FR`,
|
|
37
|
+
rotation via `^FW`/per-field orientation (last-wins), `^GB ^GC ^GD`,
|
|
38
|
+
`^GF` images (ASCII hex, Zebra RLE, B64/Z64), `~DG`/`^XG` stored
|
|
39
|
+
graphics, `^PW ^LL ^LH` (narrow `^PW` centers, never shrinks),
|
|
40
|
+
`^CC ~CC ^CT ~CT`, multi-label streams.
|
|
41
|
+
- `zpl_render` CLI (PNG/PDF by output extension, `--strict`, `--quiet`).
|
|
42
|
+
- Error hygiene: all intentional failures raise `ZplRender::Error`;
|
|
43
|
+
lenient mode collects contextual warnings, `strict: true` raises on the
|
|
44
|
+
first problem.
|
|
45
|
+
- CI matrix for Ruby 3.0-3.4 (GitHub Actions and GitLab CI) with real
|
|
46
|
+
scanner round-trip verification.
|
|
47
|
+
|
|
48
|
+
[Unreleased]: https://github.com/wqsaali/zpl_render/compare/v0.1.0...HEAD
|
|
49
|
+
[0.1.0]: https://github.com/wqsaali/zpl_render/releases/tag/v0.1.0
|
data/LICENSE.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Waqas Ali
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
|
13
|
+
all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# zpl_render
|
|
2
|
+
|
|
3
|
+
A pure-Ruby ZPL II renderer. Converts Zebra label programs (`^XA...^XZ`) to
|
|
4
|
+
**PNG** images and print-size **PDF** documents, rasterizing at true printer
|
|
5
|
+
resolution so barcodes come out module-exact and scanner-readable.
|
|
6
|
+
|
|
7
|
+
Every barcode symbology in this gem is verified in CI by rendering labels and
|
|
8
|
+
decoding them back with the [zxing-cpp](https://github.com/zxing-cpp/zxing-cpp)
|
|
9
|
+
scanner engine, at every supported rotation and at 203 and 300 dpi.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```ruby
|
|
14
|
+
gem "zpl_render"
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Runtime dependencies are pure Ruby: `chunky_png`, `rqrcode_core`, `prawn`.
|
|
18
|
+
No ImageMagick, no Java, no native extensions. Text is rasterized by a
|
|
19
|
+
built-in pure-Ruby TrueType engine from bundled Liberation fonts (SIL OFL).
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```ruby
|
|
24
|
+
require "zpl_render"
|
|
25
|
+
|
|
26
|
+
zpl = File.read("label.zpl")
|
|
27
|
+
|
|
28
|
+
# PNG (first label). dpmm: 6 = 152 dpi, 8 = 203 dpi, 12 = 300 dpi, 24 = 600 dpi
|
|
29
|
+
png = ZplRender.to_png(zpl, dpmm: 8, width_in: 4, height_in: 6)
|
|
30
|
+
File.binwrite("label.png", png)
|
|
31
|
+
|
|
32
|
+
# PDF: one page per ^XA..^XZ format, at exact physical label size
|
|
33
|
+
pdf = ZplRender.to_pdf(zpl, dpmm: 8, width_in: 4, height_in: 6)
|
|
34
|
+
File.binwrite("labels.pdf", pdf)
|
|
35
|
+
|
|
36
|
+
# All labels as PNGs, upscaled 2x for screen display
|
|
37
|
+
pngs = ZplRender.to_pngs(zpl, scale: 2)
|
|
38
|
+
|
|
39
|
+
# Collect diagnostics about unsupported commands
|
|
40
|
+
warnings = []
|
|
41
|
+
ZplRender.to_png(zpl, warnings: warnings)
|
|
42
|
+
|
|
43
|
+
# Strict mode: raise on the first problem instead of warning
|
|
44
|
+
ZplRender.to_png(zpl, strict: true)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Errors
|
|
48
|
+
|
|
49
|
+
Every intentional failure raises `ZplRender::Error` (invalid input type,
|
|
50
|
+
bad dpmm/dimensions, no `^XA..^XZ` formats, oversized barcode data in
|
|
51
|
+
strict mode). By default rendering is lenient, like a printer: a field
|
|
52
|
+
that cannot render or an unsupported command is recorded in the
|
|
53
|
+
`warnings:` array with its type and position (for example
|
|
54
|
+
`pdf417 barcode field at (21,433) failed: ...`) and rendering continues.
|
|
55
|
+
Pass `strict: true` (CLI: `--strict`) for pipelines that must not
|
|
56
|
+
silently drop label content.
|
|
57
|
+
|
|
58
|
+
### CLI
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
zpl_render label.zpl -o label.png # PNG at 203 dpi, 4x6"
|
|
62
|
+
zpl_render label.zpl -o label.pdf -d 12 # PDF at 300 dpi
|
|
63
|
+
cat label.zpl | zpl_render -o out.png -W 4 -H 2
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Barcode accuracy
|
|
67
|
+
|
|
68
|
+
Barcodes are generated from the symbology specifications, not drawn
|
|
69
|
+
approximately, and are rendered on a 1-bit dot grid with integer module
|
|
70
|
+
widths (`^BY`), exactly as a Zebra print head would lay them down:
|
|
71
|
+
|
|
72
|
+
| Symbology | ZPL | Implementation |
|
|
73
|
+
|---|---|---|
|
|
74
|
+
| Code 128 | `^BC` | Own encoder: ISO/IEC 15417 patterns, mod-103 check, ZPL subset invocation codes (`>9 >: >; >5 >6 >7 >8` ...), modes **N**, **A** (automatic packing), **U** (UCC case, SSCC-18 + mod-10) and **D** (GS1 with application identifiers, FNC1) |
|
|
75
|
+
| QR Code | `^BQ` | `rqrcode_core` (full ISO/IEC 18004: Reed-Solomon ECC, mask scoring); ZPL `<ECC><mode>,` field-data prefixes (`QA,` `HM,` ...) |
|
|
76
|
+
| PDF417 | `^B7` | Own encoder: ISO/IEC 15438 cluster patterns, Reed-Solomon over GF(929), security levels 0-8, columns/rows/truncated; verified byte-exact against FedEx ANSI MH10.8.2 payloads incl. GS/RS/EOT control characters |
|
|
77
|
+
| Code 39 | `^B3` | Full pattern table, optional mod-43 check digit |
|
|
78
|
+
| Interleaved 2 of 5 | `^B2` | Interleaved pairs, optional mod-10 check digit |
|
|
79
|
+
|
|
80
|
+
GS1-128 output is validated down to the application identifier level: a
|
|
81
|
+
scanner decodes the mode-U/D output as `(00)61414100...` etc.
|
|
82
|
+
|
|
83
|
+
## Supported commands
|
|
84
|
+
|
|
85
|
+
`^XA ^XZ` formats (multiple per stream), `^FO ^FT ^FS ^FD ^FV ^SN`,
|
|
86
|
+
fonts `^A ^A@ ^CF` with `^FB` field blocks (wrap, `\&` line breaks, L/C/R
|
|
87
|
+
justification), `^FH` hex escapes, `^CI`, field reverse `^FR`,
|
|
88
|
+
default orientation `^FW` and per-field rotation (N/R/I/B),
|
|
89
|
+
barcodes `^BY ^BC ^B3 ^B2 ^B7 ^BQ` (with interpretation lines, above/below),
|
|
90
|
+
graphics `^GB ^GC ^GD`, images `^GF` (ASCII hex, Zebra RLE compression,
|
|
91
|
+
`:B64:`/`:Z64:`) and `~DG`/`^XG` stored graphics,
|
|
92
|
+
layout `^PW ^LL ^LH`, prefix changes `^CC ~CC ^CT ~CT`, comments `^FX`.
|
|
93
|
+
Print-control commands with no visual effect (`^PQ ^MM ^MD ...`) are
|
|
94
|
+
ignored; anything else is reported through the `warnings:` array.
|
|
95
|
+
|
|
96
|
+
## Fidelity notes
|
|
97
|
+
|
|
98
|
+
- Scalable font 0 renders with Liberation Sans Bold (metrics match
|
|
99
|
+
Helvetica/Arial Bold, close to Zebra's CG Triumvirate Bold Condensed),
|
|
100
|
+
with advances and cap height calibrated against Labelary reference
|
|
101
|
+
renders. Bitmap fonts A-H render with Liberation Mono Regular at the
|
|
102
|
+
ZPL matrix cell sizes and inter-character gaps; font B is
|
|
103
|
+
uppercase-only like the hardware. On a real FedEx Ground label this
|
|
104
|
+
reproduces the reference render with ~94% pixel agreement, and
|
|
105
|
+
Code 128 output is pixel-identical. If the bundled fonts cannot be
|
|
106
|
+
loaded, an embedded public-domain 8x8 bitmap font is the fallback.
|
|
107
|
+
- `^PW` narrower than the label width is centered on the canvas and
|
|
108
|
+
never shrinks it, matching printer behavior.
|
|
109
|
+
- `^B7` PDF417 uses byte + numeric compaction; a Zebra printer may pick
|
|
110
|
+
text compaction for the same data, producing a denser but
|
|
111
|
+
identically-decoding symbol.
|
|
112
|
+
- `^BQ` mask selection is delegated to the encoder's automatic mask
|
|
113
|
+
scoring (always produces a spec-valid, scannable symbol; the printed
|
|
114
|
+
pixel pattern may differ from a printer forcing a specific mask).
|
|
115
|
+
- DataMatrix (`^BX`) and template recall (`^FN`/`^XF`) are not yet
|
|
116
|
+
implemented and are surfaced as warnings.
|
|
117
|
+
|
|
118
|
+
## Development
|
|
119
|
+
|
|
120
|
+
```
|
|
121
|
+
bundle install
|
|
122
|
+
bundle exec rspec # includes scanner round-trip tests when
|
|
123
|
+
# python3 + zxing-cpp + pillow are installed
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
CI runs the suite (with the real zxing-cpp scanner) on Ruby 3.0 through
|
|
127
|
+
3.4 via the version matrix in `.github/workflows/ci.yml` and
|
|
128
|
+
`.gitlab-ci.yml`.
|
|
129
|
+
|
|
130
|
+
### Releasing
|
|
131
|
+
|
|
132
|
+
1. Update `ZplRender::VERSION` and move the `[Unreleased]` notes to a new
|
|
133
|
+
version section in `CHANGELOG.md`.
|
|
134
|
+
2. Commit, then tag and push: `git tag v0.2.0 && git push origin main v0.2.0`.
|
|
135
|
+
|
|
136
|
+
The `Release` workflow runs the full test matrix, verifies the tag matches
|
|
137
|
+
`ZplRender::VERSION`, builds the gem, and creates a GitHub release with
|
|
138
|
+
the `.gem` attached and notes taken from the changelog. If a
|
|
139
|
+
`RUBYGEMS_API_KEY` repository secret is configured, it also publishes to
|
|
140
|
+
rubygems.org.
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
MIT. Embedded 8x8 font derived from public-domain IBM VGA fonts
|
|
145
|
+
(via Daniel Hepper's font8x8).
|
data/exe/zpl_render
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require "optparse"
|
|
5
|
+
require "zpl_render"
|
|
6
|
+
|
|
7
|
+
options = { dpmm: 8, width: 4.0, height: 6.0, scale: 1, output: nil }
|
|
8
|
+
|
|
9
|
+
parser = OptionParser.new do |opts|
|
|
10
|
+
opts.banner = <<~BANNER
|
|
11
|
+
Usage: zpl_render [options] [input.zpl]
|
|
12
|
+
|
|
13
|
+
Renders ZPL II to PNG or PDF (format chosen by output extension).
|
|
14
|
+
Reads from stdin when no input file is given.
|
|
15
|
+
BANNER
|
|
16
|
+
|
|
17
|
+
opts.on("-o", "--output FILE", "Output file (.png or .pdf). Default: label.png") { |v| options[:output] = v }
|
|
18
|
+
opts.on("-d", "--dpmm N", Integer, "Printer density in dots/mm (6, 8, 12, 24). Default: 8 (203 dpi)") { |v| options[:dpmm] = v }
|
|
19
|
+
opts.on("-W", "--width INCHES", Float, "Label width in inches (default 4)") { |v| options[:width] = v }
|
|
20
|
+
opts.on("-H", "--height INCHES", Float, "Label height in inches (default 6)") { |v| options[:height] = v }
|
|
21
|
+
opts.on("-s", "--scale N", Integer, "Integer upscale for PNG output (default 1)") { |v| options[:scale] = v }
|
|
22
|
+
opts.on("--strict", "Fail on the first problem instead of warning") { options[:strict] = true }
|
|
23
|
+
opts.on("-q", "--quiet", "Suppress warnings") { options[:quiet] = true }
|
|
24
|
+
opts.on("-v", "--version", "Print version") do
|
|
25
|
+
puts ZplRender::VERSION
|
|
26
|
+
exit
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
parser.parse!
|
|
30
|
+
|
|
31
|
+
if ARGV[0] && !File.exist?(ARGV[0])
|
|
32
|
+
warn "error: input file not found: #{ARGV[0]}"
|
|
33
|
+
exit 1
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
zpl = ARGV[0] ? File.read(ARGV[0]) : $stdin.read
|
|
37
|
+
output = options[:output] || "label.png"
|
|
38
|
+
warnings = []
|
|
39
|
+
|
|
40
|
+
begin
|
|
41
|
+
bytes = if File.extname(output).casecmp(".pdf").zero?
|
|
42
|
+
ZplRender.to_pdf(zpl, dpmm: options[:dpmm], width_in: options[:width],
|
|
43
|
+
height_in: options[:height], strict: options[:strict],
|
|
44
|
+
warnings: warnings)
|
|
45
|
+
else
|
|
46
|
+
ZplRender.to_png(zpl, dpmm: options[:dpmm], width_in: options[:width],
|
|
47
|
+
height_in: options[:height], scale: options[:scale],
|
|
48
|
+
strict: options[:strict], warnings: warnings)
|
|
49
|
+
end
|
|
50
|
+
rescue ZplRender::Error => e
|
|
51
|
+
warn "error: #{e.message}"
|
|
52
|
+
exit 1
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
begin
|
|
56
|
+
File.binwrite(output, bytes)
|
|
57
|
+
rescue SystemCallError => e
|
|
58
|
+
warn "error: cannot write #{output}: #{e.message}"
|
|
59
|
+
exit 1
|
|
60
|
+
end
|
|
61
|
+
warnings.uniq.each { |w| warn "warning: #{w}" } unless options[:quiet]
|
|
62
|
+
puts "wrote #{output}"
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ZplRender
|
|
4
|
+
module Barcode
|
|
5
|
+
# Code 128 encoder implementing ZPL ^BC semantics, including the Zebra
|
|
6
|
+
# subset invocation characters (>0 .. >;) and modes N, U, A and D.
|
|
7
|
+
#
|
|
8
|
+
# Produces the exact module sequence defined by ISO/IEC 15417: each
|
|
9
|
+
# symbol is 6 elements (11 modules), the stop pattern is 7 elements
|
|
10
|
+
# (13 modules), with a mod-103 check symbol before the stop.
|
|
11
|
+
class Code128
|
|
12
|
+
# Element widths for symbol values 0..105 (each entry: 3 bars and
|
|
13
|
+
# 3 spaces, alternating, starting with a bar).
|
|
14
|
+
PATTERNS = %w[
|
|
15
|
+
212222 222122 222221 121223 121322 131222 122213 122312 132212 221213
|
|
16
|
+
221312 231212 112232 122132 122231 113222 123122 123221 223211 221132
|
|
17
|
+
221231 213212 223112 312131 311222 321122 321221 312212 322112 322211
|
|
18
|
+
212123 212321 232121 111323 131123 131321 112313 132113 132311 211313
|
|
19
|
+
231113 231311 112133 112331 132131 113123 113321 133121 313121 211331
|
|
20
|
+
231131 213113 213311 213131 311123 311321 331121 312113 312311 332111
|
|
21
|
+
314111 221411 431111 111224 111422 121124 121421 141122 141221 112214
|
|
22
|
+
112412 122114 122411 142112 142211 241211 221114 413111 241112 134111
|
|
23
|
+
111242 121142 121241 114212 124112 124211 411212 421112 421211 212141
|
|
24
|
+
214121 412121 111143 111341 131141 114113 114311 411113 411311 113141
|
|
25
|
+
114131 311141 411131 211412 211214 211232
|
|
26
|
+
].freeze
|
|
27
|
+
STOP_PATTERN = "2331112"
|
|
28
|
+
|
|
29
|
+
CODE_C = 99
|
|
30
|
+
CODE_B = 100
|
|
31
|
+
CODE_A = 101
|
|
32
|
+
SHIFT = 98
|
|
33
|
+
FNC1 = 102
|
|
34
|
+
FNC2 = 97
|
|
35
|
+
FNC3 = 96
|
|
36
|
+
FNC4_A = 101 # FNC4 shares values with CODE A/B depending on active subset
|
|
37
|
+
FNC4_B = 100
|
|
38
|
+
START_A = 103
|
|
39
|
+
START_B = 104
|
|
40
|
+
START_C = 105
|
|
41
|
+
|
|
42
|
+
Result = Struct.new(:values, :interpretation, keyword_init: true)
|
|
43
|
+
|
|
44
|
+
# data: raw ^FD string. mode: "N", "U", "A", "D". ucc_check: bool (^BC e param)
|
|
45
|
+
def self.encode(data, mode: "N", ucc_check: false)
|
|
46
|
+
new(data.to_s, mode: mode.to_s.upcase, ucc_check: ucc_check).encode
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def initialize(data, mode:, ucc_check: false)
|
|
50
|
+
@data = data
|
|
51
|
+
@mode = mode
|
|
52
|
+
@ucc_check = ucc_check
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def encode
|
|
56
|
+
tokens = tokenize(@data)
|
|
57
|
+
case @mode
|
|
58
|
+
when "U" then encode_ucc(tokens)
|
|
59
|
+
when "A" then encode_auto(tokens, gs1: false)
|
|
60
|
+
when "D" then encode_auto(strip_gs1_decorations(tokens), gs1: true)
|
|
61
|
+
else encode_literal(tokens)
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Expand the symbol value list into a module-width string, e.g. "2122..."
|
|
66
|
+
# alternating bar/space widths, including check symbol and stop.
|
|
67
|
+
def self.modules(values)
|
|
68
|
+
sum = values.first
|
|
69
|
+
values.each_with_index { |v, i| sum += v * i unless i.zero? }
|
|
70
|
+
check = sum % 103
|
|
71
|
+
(values + [check]).map { |v| PATTERNS.fetch(v) }.join + STOP_PATTERN
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
private
|
|
75
|
+
|
|
76
|
+
# --- ZPL invocation-code tokenizer -------------------------------------
|
|
77
|
+
# Tokens: {char:}, {fnc: 1..4}, {code: :a/:b/:c}, {shift: true}, {start: :a/:b/:c}
|
|
78
|
+
INVOCATIONS = {
|
|
79
|
+
"<" => { char: "^" }, "0" => { char: ">" }, "=" => { char: "~" },
|
|
80
|
+
"1" => { char: "\x7f" }, # US in subset A / DEL in subset B; both value 95
|
|
81
|
+
"2" => { fnc: 3 }, "3" => { fnc: 2 }, "4" => { shift: true },
|
|
82
|
+
"5" => { code: :c }, "6" => { code: :b }, "7" => { code: :a },
|
|
83
|
+
"8" => { fnc: 1 },
|
|
84
|
+
"9" => { start: :a }, ":" => { start: :b }, ";" => { start: :c }
|
|
85
|
+
}.freeze
|
|
86
|
+
|
|
87
|
+
def tokenize(str)
|
|
88
|
+
tokens = []
|
|
89
|
+
i = 0
|
|
90
|
+
while i < str.length
|
|
91
|
+
ch = str[i]
|
|
92
|
+
if ch == ">" && (tok = INVOCATIONS[str[i + 1]])
|
|
93
|
+
tokens << tok.dup
|
|
94
|
+
i += 2
|
|
95
|
+
else
|
|
96
|
+
tokens << { char: ch }
|
|
97
|
+
i += 1
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
tokens
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# --- mode N: literal ZPL subset semantics -------------------------------
|
|
104
|
+
def encode_literal(tokens)
|
|
105
|
+
start = tokens.first && tokens.first[:start]
|
|
106
|
+
subset = start || :b
|
|
107
|
+
tokens = tokens.drop(1) if start
|
|
108
|
+
values = [start_value(subset)]
|
|
109
|
+
interp = +""
|
|
110
|
+
shift_next = nil
|
|
111
|
+
|
|
112
|
+
i = 0
|
|
113
|
+
while i < tokens.length
|
|
114
|
+
tok = tokens[i]
|
|
115
|
+
if tok[:start]
|
|
116
|
+
subset = tok[:start]
|
|
117
|
+
values << code_value(subset)
|
|
118
|
+
elsif tok[:code]
|
|
119
|
+
values << subset_switch_value(subset, tok[:code])
|
|
120
|
+
subset = tok[:code]
|
|
121
|
+
elsif tok[:shift]
|
|
122
|
+
shift_next = subset == :a ? :b : :a
|
|
123
|
+
values << SHIFT
|
|
124
|
+
elsif tok[:fnc]
|
|
125
|
+
values << fnc_value(subset, tok[:fnc])
|
|
126
|
+
elsif tok[:char]
|
|
127
|
+
effective = shift_next || subset
|
|
128
|
+
shift_next = nil
|
|
129
|
+
case effective
|
|
130
|
+
when :b
|
|
131
|
+
val = tok[:char].ord - 32
|
|
132
|
+
if val.between?(0, 94) || tok[:char] == "\x7f"
|
|
133
|
+
values << (tok[:char] == "\x7f" ? 95 : val)
|
|
134
|
+
interp << tok[:char] unless tok[:char] == "\x7f"
|
|
135
|
+
end
|
|
136
|
+
when :a, :c
|
|
137
|
+
# ZPL: subsets A and C are programmed as pairs of digits 00-99
|
|
138
|
+
# which map directly to symbol values.
|
|
139
|
+
nxt = tokens[i + 1]
|
|
140
|
+
if digit?(tok[:char]) && nxt && nxt[:char] && digit?(nxt[:char])
|
|
141
|
+
value = tok[:char].to_i * 10 + nxt[:char].to_i
|
|
142
|
+
values << value
|
|
143
|
+
interp << (effective == :c ? format("%02d", value) : symbol_to_char(value, :a))
|
|
144
|
+
i += 1
|
|
145
|
+
end
|
|
146
|
+
# non-digit or unpaired digit: ignored, per the ZPL manual
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
i += 1
|
|
150
|
+
end
|
|
151
|
+
finalize(values, interp)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# --- mode A / D: automatic subset optimization ---------------------------
|
|
155
|
+
def encode_auto(tokens, gs1: false)
|
|
156
|
+
items = [] # {char:} with control/fnc entries preserved
|
|
157
|
+
interp = +""
|
|
158
|
+
tokens.each do |tok|
|
|
159
|
+
if tok[:char]
|
|
160
|
+
items << { char: tok[:char] }
|
|
161
|
+
interp << tok[:char] if tok[:char] >= " " && tok[:char] != "\x7f"
|
|
162
|
+
elsif tok[:fnc]
|
|
163
|
+
items << { fnc: tok[:fnc] }
|
|
164
|
+
end
|
|
165
|
+
# explicit subset/start controls are ignored: the encoder optimizes
|
|
166
|
+
end
|
|
167
|
+
values = optimize(items, gs1: gs1)
|
|
168
|
+
finalize(values, interp)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
# UCC case mode: exactly 19 digits (padded/truncated), subset C,
|
|
172
|
+
# leading FNC1, mod-10 check digit appended.
|
|
173
|
+
def encode_ucc(tokens)
|
|
174
|
+
digits = tokens.filter_map { |t| t[:char] }.join.gsub(/\D/, "")
|
|
175
|
+
digits = digits[0, 19].rjust(19, "0")
|
|
176
|
+
full = digits + mod10_check(digits).to_s
|
|
177
|
+
values = [START_C, FNC1]
|
|
178
|
+
full.chars.each_slice(2) { |pair| values << pair.join.to_i }
|
|
179
|
+
finalize(values, full)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def strip_gs1_decorations(tokens)
|
|
183
|
+
out = []
|
|
184
|
+
tokens.each do |tok|
|
|
185
|
+
next if tok[:char] == "(" || tok[:char] == ")" || tok[:char] == " "
|
|
186
|
+
|
|
187
|
+
out << tok
|
|
188
|
+
end
|
|
189
|
+
# Mode D always starts with FNC1 (UCC/EAN-128)
|
|
190
|
+
out.unshift(fnc: 1) unless out.first && out.first[:fnc] == 1
|
|
191
|
+
out
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
# Greedy subset optimizer (Zebra mode A behavior: a run of 4+ digits,
|
|
195
|
+
# or an all-digit even-length tail, switches to subset C).
|
|
196
|
+
def optimize(items, gs1: false)
|
|
197
|
+
values = []
|
|
198
|
+
subset = nil
|
|
199
|
+
i = 0
|
|
200
|
+
|
|
201
|
+
while i < items.length
|
|
202
|
+
item = items[i]
|
|
203
|
+
if item[:fnc]
|
|
204
|
+
if subset.nil?
|
|
205
|
+
subset = digits_ahead(items, i + 1) >= 4 ? :c : :b
|
|
206
|
+
values << start_value(subset)
|
|
207
|
+
end
|
|
208
|
+
values << fnc_value(subset, item[:fnc])
|
|
209
|
+
i += 1
|
|
210
|
+
next
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
run = digit_run(items, i)
|
|
214
|
+
if run >= 4 || (run >= 2 && run == items.length - i && run.even? && i.zero?)
|
|
215
|
+
run -= 1 if run.odd?
|
|
216
|
+
if subset.nil?
|
|
217
|
+
values << START_C
|
|
218
|
+
elsif subset != :c
|
|
219
|
+
values << CODE_C
|
|
220
|
+
end
|
|
221
|
+
subset = :c
|
|
222
|
+
(run / 2).times do
|
|
223
|
+
values << (items[i][:char].to_i * 10 + items[i + 1][:char].to_i)
|
|
224
|
+
i += 2
|
|
225
|
+
end
|
|
226
|
+
next
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
ch = item[:char]
|
|
230
|
+
target = ch.ord < 32 ? :a : :b
|
|
231
|
+
if subset.nil?
|
|
232
|
+
subset = target
|
|
233
|
+
values << start_value(subset)
|
|
234
|
+
elsif subset == :c || subset != target
|
|
235
|
+
# single opposite-subset char inside a run: use SHIFT, else CODE
|
|
236
|
+
if subset != :c && single_exception?(items, i, subset)
|
|
237
|
+
values << SHIFT
|
|
238
|
+
values << char_value(ch, target)
|
|
239
|
+
i += 1
|
|
240
|
+
next
|
|
241
|
+
end
|
|
242
|
+
values << subset_switch_value(subset, target)
|
|
243
|
+
subset = target
|
|
244
|
+
end
|
|
245
|
+
values << char_value(ch, subset)
|
|
246
|
+
i += 1
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
values = [START_B] if values.empty?
|
|
250
|
+
values.unshift(START_B) unless values.first.between?(START_A, START_C)
|
|
251
|
+
values
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def digit_run(items, i)
|
|
255
|
+
run = 0
|
|
256
|
+
run += 1 while (item = items[i + run]) && item[:char] && digit?(item[:char])
|
|
257
|
+
run
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
def digits_ahead(items, i)
|
|
261
|
+
digit_run(items, i)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
# true when items[i] needs the other subset but items[i+1] fits the current
|
|
265
|
+
def single_exception?(items, i, subset)
|
|
266
|
+
nxt = items[i + 1]
|
|
267
|
+
return false unless nxt && nxt[:char]
|
|
268
|
+
|
|
269
|
+
nxt_target = nxt[:char].ord < 32 ? :a : :b
|
|
270
|
+
nxt_target == subset
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
def char_value(ch, subset)
|
|
274
|
+
if subset == :a
|
|
275
|
+
ch.ord < 32 ? ch.ord + 64 : ch.ord - 32
|
|
276
|
+
else
|
|
277
|
+
ch == "\x7f" ? 95 : ch.ord - 32
|
|
278
|
+
end
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
def digit?(ch)
|
|
282
|
+
ch >= "0" && ch <= "9"
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
def symbol_to_char(value, _subset)
|
|
286
|
+
value <= 63 ? (value + 32).chr : ""
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
def start_value(subset)
|
|
290
|
+
{ a: START_A, b: START_B, c: START_C }.fetch(subset)
|
|
291
|
+
end
|
|
292
|
+
|
|
293
|
+
def code_value(subset)
|
|
294
|
+
{ a: CODE_A, b: CODE_B, c: CODE_C }.fetch(subset)
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
def subset_switch_value(_from, to)
|
|
298
|
+
code_value(to)
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
def fnc_value(subset, n)
|
|
302
|
+
case n
|
|
303
|
+
when 1 then FNC1
|
|
304
|
+
when 2 then FNC2
|
|
305
|
+
when 3 then FNC3
|
|
306
|
+
when 4 then subset == :a ? FNC4_A : FNC4_B
|
|
307
|
+
end
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
def mod10_check(digits)
|
|
311
|
+
sum = 0
|
|
312
|
+
digits.reverse.each_char.with_index do |c, i|
|
|
313
|
+
sum += c.to_i * (i.even? ? 3 : 1)
|
|
314
|
+
end
|
|
315
|
+
(10 - (sum % 10)) % 10
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
def finalize(values, interp)
|
|
319
|
+
if @ucc_check && @mode != "U"
|
|
320
|
+
# ^BC e=Y appends a mod-10 check digit over the interpretation digits
|
|
321
|
+
digits = interp.gsub(/\D/, "")
|
|
322
|
+
unless digits.empty?
|
|
323
|
+
check = mod10_check(digits)
|
|
324
|
+
interp += check.to_s
|
|
325
|
+
values << check if values.last && values.last < 100 # only extend subset C data
|
|
326
|
+
end
|
|
327
|
+
end
|
|
328
|
+
Result.new(values: values, interpretation: interp)
|
|
329
|
+
end
|
|
330
|
+
end
|
|
331
|
+
end
|
|
332
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ZplRender
|
|
4
|
+
module Barcode
|
|
5
|
+
# Code 39 encoder (ZPL ^B3). Each character is 9 elements (5 bars,
|
|
6
|
+
# 4 spaces), 3 of them wide. Start/stop character '*' is added
|
|
7
|
+
# automatically, elements are separated by a narrow inter-character gap.
|
|
8
|
+
class Code39
|
|
9
|
+
# n = narrow, w = wide; elements alternate bar/space starting with a bar
|
|
10
|
+
PATTERNS = {
|
|
11
|
+
"0" => "nnnwwnwnn", "1" => "wnnwnnnnw", "2" => "nnwwnnnnw",
|
|
12
|
+
"3" => "wnwwnnnnn", "4" => "nnnwwnnnw", "5" => "wnnwwnnnn",
|
|
13
|
+
"6" => "nnwwwnnnn", "7" => "nnnwnnwnw", "8" => "wnnwnnwnn",
|
|
14
|
+
"9" => "nnwwnnwnn", "A" => "wnnnnwnnw", "B" => "nnwnnwnnw",
|
|
15
|
+
"C" => "wnwnnwnnn", "D" => "nnnnwwnnw", "E" => "wnnnwwnnn",
|
|
16
|
+
"F" => "nnwnwwnnn", "G" => "nnnnnwwnw", "H" => "wnnnnwwnn",
|
|
17
|
+
"I" => "nnwnnwwnn", "J" => "nnnnwwwnn", "K" => "wnnnnnnww",
|
|
18
|
+
"L" => "nnwnnnnww", "M" => "wnwnnnnwn", "N" => "nnnnwnnww",
|
|
19
|
+
"O" => "wnnnwnnwn", "P" => "nnwnwnnwn", "Q" => "nnnnnnwww",
|
|
20
|
+
"R" => "wnnnnnwwn", "S" => "nnwnnnwwn", "T" => "nnnnwnwwn",
|
|
21
|
+
"U" => "wwnnnnnnw", "V" => "nwwnnnnnw", "W" => "wwwnnnnnn",
|
|
22
|
+
"X" => "nwnnwnnnw", "Y" => "wwnnwnnnn", "Z" => "nwwnwnnnn",
|
|
23
|
+
"-" => "nwnnnnwnw", "." => "wwnnnnwnn", " " => "nwwnnnwnn",
|
|
24
|
+
"$" => "nwnwnwnnn", "/" => "nwnwnnnwn", "+" => "nwnnnwnwn",
|
|
25
|
+
"%" => "nnnwnwnwn", "*" => "nwnnwnwnn"
|
|
26
|
+
}.freeze
|
|
27
|
+
|
|
28
|
+
CHECK_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%"
|
|
29
|
+
|
|
30
|
+
Result = Struct.new(:elements, :interpretation, keyword_init: true)
|
|
31
|
+
|
|
32
|
+
# Returns elements as [[width_units, bar?], ...] where width_units is
|
|
33
|
+
# 1 (narrow) or the wide ratio, to be multiplied by the module width.
|
|
34
|
+
def self.encode(data, check_digit: false)
|
|
35
|
+
text = data.to_s.upcase.gsub(/[^0-9A-Z\-\. $\/+%]/, "")
|
|
36
|
+
payload = text.dup
|
|
37
|
+
if check_digit
|
|
38
|
+
sum = payload.chars.sum { |c| CHECK_CHARS.index(c) || 0 }
|
|
39
|
+
payload += CHECK_CHARS[sum % 43]
|
|
40
|
+
end
|
|
41
|
+
full = "*#{payload}*"
|
|
42
|
+
elements = []
|
|
43
|
+
full.each_char.with_index do |ch, idx|
|
|
44
|
+
PATTERNS.fetch(ch).each_char.with_index do |wide, i|
|
|
45
|
+
elements << [wide == "w" ? :wide : :narrow, i.even?]
|
|
46
|
+
end
|
|
47
|
+
elements << [:narrow, false] unless idx == full.length - 1 # inter-char gap
|
|
48
|
+
end
|
|
49
|
+
Result.new(elements: elements, interpretation: text)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|