0
# Writing Barcodes
1
2
ZXing-C++ provides comprehensive barcode writing capabilities through the MultiFormatWriter class, supporting most major barcode formats with customizable encoding parameters.
3
4
## MultiFormatWriter Class
5
6
The primary interface for creating barcodes in any supported format.
7
8
```cpp { .api }
9
class MultiFormatWriter {
10
public:
11
explicit MultiFormatWriter(BarcodeFormat format);
12
13
MultiFormatWriter& setEncoding(CharacterSet encoding);
14
MultiFormatWriter& setEccLevel(int level);
15
MultiFormatWriter& setMargin(int margin);
16
17
BitMatrix encode(const std::wstring& contents, int width, int height) const;
18
BitMatrix encode(const std::string& contents, int width, int height) const;
19
};
20
```
21
22
### Constructor
23
24
```cpp { .api }
25
explicit MultiFormatWriter(BarcodeFormat format);
26
```
27
28
Creates a writer for the specified barcode format.
29
30
**Parameters:**
31
- `format`: The barcode format to generate (e.g., BarcodeFormat::QRCode)
32
33
### Configuration Methods
34
35
#### Set Character Encoding
36
37
```cpp { .api }
38
MultiFormatWriter& setEncoding(CharacterSet encoding);
39
```
40
41
Set the character encoding for text content. Used for Aztec, PDF417, and QRCode only.
42
43
**Parameters:**
44
- `encoding`: Character set to use (e.g., CharacterSet::UTF8)
45
46
**Returns:** Reference to this writer for method chaining
47
48
#### Set Error Correction Level
49
50
```cpp { .api }
51
MultiFormatWriter& setEccLevel(int level);
52
```
53
54
Set the error correction level. Used for Aztec, PDF417, and QRCode only.
55
56
**Parameters:**
57
- `level`: Error correction level (0-8, meaning varies by format)
58
59
**Returns:** Reference to this writer for method chaining
60
61
#### Set Margin
62
63
```cpp { .api }
64
MultiFormatWriter& setMargin(int margin);
65
```
66
67
Set the quiet zone margin around the barcode.
68
69
**Parameters:**
70
- `margin`: Minimum number of quiet zone pixels/modules
71
72
**Returns:** Reference to this writer for method chaining
73
74
### Encoding Methods
75
76
#### Encode String Content
77
78
```cpp { .api }
79
BitMatrix encode(const std::string& contents, int width, int height) const;
80
BitMatrix encode(const std::wstring& contents, int width, int height) const;
81
```
82
83
Generate a barcode from text content.
84
85
**Parameters:**
86
- `contents`: Text content to encode
87
- `width`: Desired output width in pixels
88
- `height`: Desired output height in pixels
89
90
**Returns:** BitMatrix representing the barcode (true = black, false = white)
91
92
## Usage Examples
93
94
### Basic QR Code Generation
95
96
```cpp
97
#include "MultiFormatWriter.h"
98
#include "BitMatrix.h"
99
#include "BarcodeFormat.h"
100
101
using namespace ZXing;
102
103
// Create QR Code writer
104
MultiFormatWriter writer(BarcodeFormat::QRCode);
105
106
// Generate barcode
107
BitMatrix matrix = writer.encode("Hello, World!", 200, 200);
108
109
// Convert to your image format
110
for (int y = 0; y < matrix.height(); ++y) {
111
for (int x = 0; x < matrix.width(); ++x) {
112
bool isBlack = matrix.get(x, y);
113
// Set pixel in your image buffer
114
// Black pixels: isBlack == true
115
// White pixels: isBlack == false
116
}
117
}
118
```
119
120
### QR Code with Custom Settings
121
122
```cpp
123
MultiFormatWriter writer(BarcodeFormat::QRCode);
124
125
// Configure the writer
126
writer.setEncoding(CharacterSet::UTF8) // Support Unicode
127
.setEccLevel(2) // Medium error correction
128
.setMargin(20); // 20-pixel quiet zone
129
130
// Generate larger QR code
131
BitMatrix matrix = writer.encode("https://example.com/path?param=value", 400, 400);
132
```
133
134
### Different Barcode Formats
135
136
```cpp
137
// Code 128 (1D barcode)
138
MultiFormatWriter code128Writer(BarcodeFormat::Code128);
139
BitMatrix code128 = code128Writer.encode("12345ABCDE", 300, 100);
140
141
// DataMatrix (2D barcode)
142
MultiFormatWriter dmWriter(BarcodeFormat::DataMatrix);
143
BitMatrix dataMatrix = dmWriter.encode("Data content here", 200, 200);
144
145
// PDF417 (stacked 2D barcode)
146
MultiFormatWriter pdf417Writer(BarcodeFormat::PDF417);
147
pdf417Writer.setEccLevel(5); // High error correction
148
BitMatrix pdf417 = pdf417Writer.encode("PDF417 content with lots of data", 400, 200);
149
150
// Aztec code
151
MultiFormatWriter aztecWriter(BarcodeFormat::Aztec);
152
aztecWriter.setEccLevel(3);
153
BitMatrix aztec = aztecWriter.encode("Aztec barcode content", 300, 300);
154
```
155
156
### Converting BitMatrix to Image
157
158
```cpp
159
#include "BitMatrix.h"
160
161
// Example: Convert to RGB image data
162
void bitMatrixToRGB(const BitMatrix& matrix, std::vector<uint8_t>& rgbData) {
163
int width = matrix.width();
164
int height = matrix.height();
165
rgbData.resize(width * height * 3);
166
167
for (int y = 0; y < height; ++y) {
168
for (int x = 0; x < width; ++x) {
169
int index = (y * width + x) * 3;
170
uint8_t color = matrix.get(x, y) ? 0 : 255; // Black or white
171
172
rgbData[index] = color; // Red
173
rgbData[index + 1] = color; // Green
174
rgbData[index + 2] = color; // Blue
175
}
176
}
177
}
178
179
// Usage
180
MultiFormatWriter writer(BarcodeFormat::QRCode);
181
BitMatrix matrix = writer.encode("Test", 200, 200);
182
183
std::vector<uint8_t> imageData;
184
bitMatrixToRGB(matrix, imageData);
185
```
186
187
### Saving to Common Image Formats
188
189
```cpp
190
#include "BitMatrixIO.h" // For utility functions
191
192
// Using STB image library (example)
193
#define STB_IMAGE_WRITE_IMPLEMENTATION
194
#include <stb_image_write.h>
195
196
void saveBarcodeAsPNG(const BitMatrix& matrix, const std::string& filename) {
197
int width = matrix.width();
198
int height = matrix.height();
199
200
// Convert to grayscale
201
std::vector<uint8_t> grayData(width * height);
202
for (int y = 0; y < height; ++y) {
203
for (int x = 0; x < width; ++x) {
204
grayData[y * width + x] = matrix.get(x, y) ? 0 : 255;
205
}
206
}
207
208
// Save as PNG
209
stbi_write_png(filename.c_str(), width, height, 1, grayData.data(), width);
210
}
211
212
// Usage
213
MultiFormatWriter writer(BarcodeFormat::QRCode);
214
BitMatrix matrix = writer.encode("https://example.com", 300, 300);
215
saveBarcodeAsPNG(matrix, "qrcode.png");
216
```
217
218
### Unicode Content
219
220
```cpp
221
// Using wide string for Unicode content
222
std::wstring unicodeContent = L"Hello δΈη! π";
223
224
MultiFormatWriter writer(BarcodeFormat::QRCode);
225
writer.setEncoding(CharacterSet::UTF8);
226
227
BitMatrix matrix = writer.encode(unicodeContent, 250, 250);
228
229
// Or using UTF-8 encoded std::string
230
std::string utf8Content = "Hello δΈη! π";
231
BitMatrix matrix2 = writer.encode(utf8Content, 250, 250);
232
```
233
234
## Supported Formats for Writing
235
236
Most formats support writing (DataBar formats are read-only):
237
238
### Linear Barcodes
239
- **UPC-A / UPC-E**: 12/8-digit numeric product codes
240
- **EAN-8 / EAN-13**: 8/13-digit numeric product codes
241
- **Code 39**: Alphanumeric with start/stop characters
242
- **Code 93**: More compact alphanumeric format
243
- **Code 128**: High-density alphanumeric format
244
- **Codabar**: Numeric format for libraries/medical
245
- **ITF**: 14-digit numeric format for packaging
246
247
### Matrix Barcodes
248
- **QR Code**: Square format with high capacity and error correction
249
- **DataMatrix**: Square/rectangular format for industrial use
250
- **Aztec**: Compact square format with center pattern
251
- **PDF417**: Stacked 2D format with high data capacity
252
253
## Format-Specific Guidelines
254
255
### QR Code
256
- **Error Correction Levels**: 0 (L~7%), 1 (M~15%), 2 (Q~25%), 3 (H~30%)
257
- **Capacity**: Up to 4,296 alphanumeric characters
258
- **Optimal Size**: At least 21Γ21 modules, scales with content
259
260
### DataMatrix
261
- **Error Correction**: Reed-Solomon (automatic level selection)
262
- **Capacity**: Up to 2,335 alphanumeric characters
263
- **Sizes**: Square (10Γ10 to 144Γ144) or rectangular
264
265
### PDF417
266
- **Error Correction Levels**: 0-8 (higher = more redundancy)
267
- **Aspect Ratio**: Typically rectangular (width > height)
268
- **Capacity**: Up to 1,850 alphanumeric characters
269
270
### Code 128
271
- **Character Sets**: Automatic selection (A, B, C)
272
- **Content**: All ASCII characters
273
- **Check Digits**: Automatically calculated
274
275
### Linear Formats (UPC/EAN)
276
- **Fixed Length**: UPC-A (12), UPC-E (8), EAN-13 (13), EAN-8 (8)
277
- **Check Digits**: Automatically calculated
278
- **Content**: Numeric only
279
280
## Error Handling
281
282
The encode() methods may throw exceptions for invalid input:
283
284
```cpp
285
try {
286
MultiFormatWriter writer(BarcodeFormat::EAN13);
287
// This will throw - EAN-13 requires exactly 13 digits
288
BitMatrix matrix = writer.encode("12345", 200, 100);
289
} catch (const std::exception& e) {
290
std::cout << "Encoding error: " << e.what() << std::endl;
291
}
292
```
293
294
## Character Set Options
295
296
```cpp { .api }
297
enum class CharacterSet {
298
Unknown,
299
ASCII,
300
ISO8859_1, ISO8859_2, ISO8859_3, ISO8859_4, ISO8859_5,
301
ISO8859_6, ISO8859_7, ISO8859_8, ISO8859_9, ISO8859_10,
302
ISO8859_11, ISO8859_13, ISO8859_14, ISO8859_15, ISO8859_16,
303
Cp437, Cp1250, Cp1251, Cp1252, Cp1256,
304
Shift_JIS, Big5, GB2312, GB18030, EUC_JP, EUC_KR,
305
UnicodeBig, UTF8, BINARY
306
};
307
```
308
309
## Performance Tips
310
311
1. **Choose appropriate size**: Larger sizes provide better scanning reliability
312
2. **Use adequate quiet zones**: Set margin to at least 4 modules for linear codes
313
3. **Consider error correction**: Higher levels improve reliability but reduce capacity
314
4. **Validate content**: Ensure content matches format requirements before encoding
315
5. **Reuse writers**: Create writer once and call encode() multiple times for same format