0
# String Output Rendering
1
2
String-based QR code rendering functionality that generates QR codes in multiple text and markup formats including UTF-8, SVG, and terminal output.
3
4
**Note**: In browser environments, `toString` only supports SVG output format. UTF-8 and terminal output formats are available only in Node.js environments.
5
6
## Capabilities
7
8
### String Output Generation
9
10
Generates string representations of QR codes in various formats.
11
12
```javascript { .api }
13
/**
14
* Returns a string representation of the QR Code
15
* @param {string|Array} text - Text to encode or segments
16
* @param {Object} options - String rendering options
17
* @param {Function} callback - Callback with (error, string)
18
* @returns {Promise<string>} String when using promises
19
*/
20
function toString(text, options, callback);
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
const QRCode = require('qrcode');
27
28
// UTF-8 text output (default)
29
QRCode.toString('Hello World', function (err, string) {
30
if (err) throw err;
31
console.log(string);
32
// Outputs ASCII art representation:
33
// █████████████████████████████
34
// █████████████████████████████
35
// ████ ▄▄▄▄▄ █▀▄█▀█ ▄▄▄▄▄ ████
36
// ████ █ █ █▄▀▀▀▄█ █ █ ████
37
// ...
38
});
39
40
// SVG output
41
QRCode.toString('Hello World', { type: 'svg' }, function (err, string) {
42
if (err) throw err;
43
console.log(string);
44
// Outputs complete SVG markup:
45
// <svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...
46
});
47
48
// Terminal output (colorized for terminals)
49
QRCode.toString('Hello World', { type: 'terminal' }, function (err, string) {
50
if (err) throw err;
51
console.log(string);
52
// Outputs terminal-optimized representation with ANSI colors
53
});
54
55
// Using Promises
56
try {
57
const svgString = await QRCode.toString('Hello World', { type: 'svg' });
58
const textString = await QRCode.toString('Hello World', { type: 'utf8' });
59
const terminalString = await QRCode.toString('Hello World', { type: 'terminal' });
60
} catch (err) {
61
console.error(err);
62
}
63
```
64
65
## Output Format Types
66
67
### UTF-8 Text Output
68
69
Plain text representation using Unicode block characters.
70
71
```javascript { .api }
72
interface UTF8Options {
73
/** Output format */
74
type: 'utf8';
75
/** Standard rendering options apply */
76
margin?: number;
77
scale?: number;
78
small?: boolean; // Compact output (terminal renderer only)
79
inverse?: boolean; // Invert colors (terminal renderer only)
80
}
81
```
82
83
**Examples:**
84
85
```javascript
86
// Standard UTF-8 output
87
const textQR = await QRCode.toString('Hello', { type: 'utf8' });
88
console.log(textQR);
89
// █████████████████████████████
90
// █████████████████████████████
91
// ████ ▄▄▄▄▄ █▀▄█▀█ ▄▄▄▄▄ ████
92
// ████ █ █ █▄▀▀▀▄█ █ █ ████
93
// ████ █▄▄▄█ ██▄▀▀▄█ █▄▄▄█ ████
94
95
// Compact UTF-8 output
96
const compactQR = await QRCode.toString('Hello', {
97
type: 'utf8',
98
small: true
99
});
100
// Smaller representation using different Unicode characters
101
```
102
103
### SVG Output
104
105
Complete SVG markup for web and vector graphics use.
106
107
```javascript { .api }
108
interface SVGOptions {
109
/** Output format */
110
type: 'svg';
111
/** SVG-specific options */
112
width?: number; // SVG width
113
margin?: number; // Quiet zone margin
114
color?: {
115
dark?: string; // Dark module color
116
light?: string; // Light module color
117
};
118
}
119
```
120
121
**Examples:**
122
123
```javascript
124
// Basic SVG
125
const svgString = await QRCode.toString('Hello World', { type: 'svg' });
126
// <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 25 25">
127
// <rect width="25" height="25" fill="#ffffff"/>
128
// <rect x="0" y="0" width="1" height="1" fill="#000000"/>
129
// ...
130
// </svg>
131
132
// Styled SVG
133
const styledSVG = await QRCode.toString('Styled QR', {
134
type: 'svg',
135
width: 300,
136
margin: 4,
137
color: {
138
dark: '#0066CC',
139
light: '#FFFFFF'
140
}
141
});
142
143
// SVG with transparent background
144
const transparentSVG = await QRCode.toString('Transparent', {
145
type: 'svg',
146
color: {
147
dark: '#000000',
148
light: '#00000000' // Transparent background
149
}
150
});
151
```
152
153
### Terminal Output
154
155
Terminal-optimized output with ANSI color support.
156
157
```javascript { .api }
158
interface TerminalOptions {
159
/** Output format */
160
type: 'terminal';
161
/** Terminal-specific options */
162
small?: boolean; // Compact terminal output
163
inverse?: boolean; // Invert foreground/background colors
164
}
165
```
166
167
**Examples:**
168
169
```javascript
170
// Standard terminal output
171
const terminalQR = await QRCode.toString('Terminal QR', {
172
type: 'terminal'
173
});
174
console.log(terminalQR);
175
// Outputs with ANSI escape codes for proper terminal display
176
177
// Compact terminal output
178
const smallQR = await QRCode.toString('Small QR', {
179
type: 'terminal',
180
small: true
181
});
182
183
// Inverted colors
184
const invertedQR = await QRCode.toString('Inverted', {
185
type: 'terminal',
186
inverse: true
187
});
188
```
189
190
## Browser Usage
191
192
### SVG in Web Pages
193
194
```javascript
195
// Generate SVG for web display
196
QRCode.toString('Web QR Code', { type: 'svg' }, function (err, svgString) {
197
if (err) throw err;
198
199
// Insert directly into DOM
200
document.getElementById('qr-container').innerHTML = svgString;
201
202
// Or create SVG element
203
const parser = new DOMParser();
204
const svgDoc = parser.parseFromString(svgString, 'image/svg+xml');
205
const svgElement = svgDoc.documentElement;
206
document.body.appendChild(svgElement);
207
});
208
209
// Styled SVG for web
210
QRCode.toString('Styled Web QR', {
211
type: 'svg',
212
width: 250,
213
color: {
214
dark: '#2E8B57', // Sea green
215
light: '#F0F8FF' // Alice blue
216
}
217
}, function (err, svgString) {
218
document.getElementById('styled-qr').innerHTML = svgString;
219
});
220
```
221
222
### React Integration
223
224
```javascript
225
import React, { useState, useEffect } from 'react';
226
import QRCode from 'qrcode';
227
228
function SVGQRCode({ text, options = {} }) {
229
const [svgString, setSvgString] = useState('');
230
231
useEffect(() => {
232
QRCode.toString(text, { type: 'svg', ...options })
233
.then(setSvgString)
234
.catch(console.error);
235
}, [text, options]);
236
237
return (
238
<div
239
dangerouslySetInnerHTML={{ __html: svgString }}
240
style={{ display: 'inline-block' }}
241
/>
242
);
243
}
244
245
// Usage
246
<SVGQRCode
247
text="React QR Code"
248
options={{
249
width: 200,
250
color: { dark: '#FF6B6B', light: '#4ECDC4' }
251
}}
252
/>
253
```
254
255
### Vue Integration
256
257
```javascript
258
// Vue component using SVG string
259
export default {
260
props: ['text', 'options'],
261
data() {
262
return {
263
svgString: ''
264
};
265
},
266
watch: {
267
text: 'generateQR',
268
options: 'generateQR'
269
},
270
mounted() {
271
this.generateQR();
272
},
273
methods: {
274
async generateQR() {
275
try {
276
this.svgString = await QRCode.toString(this.text, {
277
type: 'svg',
278
...this.options
279
});
280
} catch (err) {
281
console.error(err);
282
}
283
}
284
},
285
template: `<div v-html="svgString"></div>`
286
};
287
```
288
289
## Node.js Usage
290
291
### CLI Applications
292
293
```javascript
294
#!/usr/bin/env node
295
const QRCode = require('qrcode');
296
297
// Terminal QR code display
298
async function displayQR(text) {
299
try {
300
const qrString = await QRCode.toString(text, {
301
type: 'terminal',
302
small: process.stdout.columns < 80 // Adapt to terminal width
303
});
304
console.log(qrString);
305
} catch (err) {
306
console.error('QR generation failed:', err.message);
307
}
308
}
309
310
// Usage: node qr-display.js "Hello World"
311
displayQR(process.argv[2] || 'Default Text');
312
```
313
314
### File Generation
315
316
```javascript
317
const fs = require('fs');
318
const QRCode = require('qrcode');
319
320
// Generate SVG file
321
async function generateSVGFile(text, filename) {
322
try {
323
const svgString = await QRCode.toString(text, {
324
type: 'svg',
325
width: 400,
326
margin: 2
327
});
328
329
fs.writeFileSync(filename, svgString, 'utf8');
330
console.log(`SVG QR code saved to ${filename}`);
331
} catch (err) {
332
console.error('SVG generation failed:', err);
333
}
334
}
335
336
// Generate text file
337
async function generateTextFile(text, filename) {
338
try {
339
const textString = await QRCode.toString(text, { type: 'utf8' });
340
341
fs.writeFileSync(filename, textString, 'utf8');
342
console.log(`Text QR code saved to ${filename}`);
343
} catch (err) {
344
console.error('Text generation failed:', err);
345
}
346
}
347
348
// Usage
349
generateSVGFile('SVG QR Code', 'qr.svg');
350
generateTextFile('Text QR Code', 'qr.txt');
351
```
352
353
### Email Templates
354
355
```javascript
356
const QRCode = require('qrcode');
357
358
// Generate SVG for HTML email
359
async function generateEmailQR(url, options = {}) {
360
try {
361
const svgString = await QRCode.toString(url, {
362
type: 'svg',
363
width: 150,
364
margin: 1,
365
color: {
366
dark: '#000000',
367
light: '#FFFFFF'
368
},
369
...options
370
});
371
372
// SVG can be embedded directly in HTML emails
373
return `
374
<div style="text-align: center;">
375
<p>Scan to visit:</p>
376
${svgString}
377
<p><a href="${url}">${url}</a></p>
378
</div>
379
`;
380
} catch (err) {
381
console.error('Email QR generation failed:', err);
382
return `<p>QR Code generation failed</p>`;
383
}
384
}
385
```
386
387
## Advanced String Rendering
388
389
### Custom Styling
390
391
```javascript
392
// High-contrast SVG for accessibility
393
const accessibleQR = await QRCode.toString('Accessible QR', {
394
type: 'svg',
395
width: 300,
396
margin: 4,
397
color: {
398
dark: '#000000', // Pure black
399
light: '#FFFFFF' // Pure white
400
}
401
});
402
403
// Branded SVG with custom colors
404
const brandedQR = await QRCode.toString('Brand QR', {
405
type: 'svg',
406
width: 250,
407
color: {
408
dark: '#FF6B35', // Brand orange
409
light: '#F7F7F7' // Light gray
410
}
411
});
412
```
413
414
### Multiple Format Generation
415
416
```javascript
417
// Generate all formats for the same data
418
async function generateAllFormats(text) {
419
const formats = ['utf8', 'svg', 'terminal'];
420
const results = {};
421
422
for (const format of formats) {
423
try {
424
results[format] = await QRCode.toString(text, { type: format });
425
} catch (err) {
426
results[format] = `Error: ${err.message}`;
427
}
428
}
429
430
return results;
431
}
432
433
// Usage
434
const allFormats = await generateAllFormats('Multi-format QR');
435
console.log('UTF-8:', allFormats.utf8);
436
console.log('SVG length:', allFormats.svg.length);
437
console.log('Terminal output ready:', allFormats.terminal.includes('\x1b'));
438
```
439
440
## Error Handling
441
442
String rendering functions handle format-specific errors:
443
444
```javascript
445
// Invalid format type
446
QRCode.toString('text', { type: 'invalid' }, function (err, string) {
447
if (err) {
448
console.log(err.message); // Format-specific error
449
}
450
});
451
452
// Data too large for string rendering
453
QRCode.toString('x'.repeat(8000), { type: 'svg' }, function (err, string) {
454
if (err) {
455
console.log(err.message); // "The amount of data is too big..."
456
}
457
});
458
459
// Terminal-specific errors
460
QRCode.toString('text', {
461
type: 'terminal',
462
invalidOption: true
463
}, function (err, string) {
464
if (err) {
465
console.log(err.message); // Option validation error
466
}
467
});
468
```