6d50cbf29edded90d67142c2a2ce3cf2e56636fe
[platform/framework/web/wrtjs.git] / device_home / node_modules / qrcode / README.md
1 # node-qrcode
2 > QR code/2d barcode generator.
3
4 [![Travis](https://img.shields.io/travis/soldair/node-qrcode.svg?style=flat-square)](http://travis-ci.org/soldair/node-qrcode)
5 [![npm](https://img.shields.io/npm/v/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode)
6 [![npm](https://img.shields.io/npm/dt/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode)
7 [![npm](https://img.shields.io/npm/l/qrcode.svg?style=flat-square)](https://github.com/soldair/node-qrcode/blob/master/license)
8
9 - [Highlights](#highlights)
10 - [Installation](#installation)
11 - [Usage](#usage)
12 - [Error correction level](#error-correction-level)
13 - [QR Code capacity](#qr-code-capacity)
14 - [Encoding Modes](#encoding-modes)
15 - [Binary data](#binary-data)
16 - [Multibyte characters](#multibyte-characters)
17 - [API](#api)
18 - [GS1 QR Codes](#gs1)
19 - [Credits](#credits)
20 - [License](#license)
21
22 ## Highlights
23 - Works on server and client (and react native with svg)
24 - CLI utility
25 - Save QR code as image
26 - Support for Numeric, Alphanumeric, Kanji and Byte mode
27 - Support for mixed modes
28 - Support for chinese, cyrillic, greek and japanese characters
29 - Support for multibyte characters (like emojis :smile:)
30 - Auto generates optimized segments for best data compression and smallest QR Code size
31 - App agnostic readability, QR Codes by definition are app agnostic
32
33 ## Installation
34 Inside your project folder do:
35
36 ```shell
37 npm install --save qrcode
38 ```
39
40 or, install it globally to use `qrcode` from the command line to save qrcode images or generate ones you can view in your terminal.
41
42 ```shell
43 npm install -g qrcode
44 ```
45
46 ## Usage
47 ### CLI
48
49 ```
50 Usage: qrcode [options] <input string>
51
52 QR Code options:
53   -v, --qversion  QR Code symbol version (1 - 40)                       [number]
54   -e, --error     Error correction level           [choices: "L", "M", "Q", "H"]
55   -m, --mask      Mask pattern (0 - 7)                                  [number]
56
57 Renderer options:
58   -t, --type        Output type                  [choices: "png", "svg", "utf8"]
59   -w, --width       Image width (px)                                    [number]
60   -s, --scale       Scale factor                                        [number]
61   -q, --qzone       Quiet zone size                                     [number]
62   -l, --lightcolor  Light RGBA hex color
63   -d, --darkcolor   Dark RGBA hex color
64
65 Options:
66   -o, --output  Output file
67   -h, --help    Show help                                              [boolean]
68   --version     Show version number                                    [boolean]
69
70 Examples:
71   qrcode "some text"                    Draw in terminal window
72   qrcode -o out.png "some text"         Save as png image
73   qrcode -d F00 -o out.png "some text"  Use red as foreground color
74 ```
75 If not specified, output type is guessed from file extension.<br>
76 Recognized extensions are `png`, `svg` and `txt`.
77
78 ### Browser
79 `node-qrcode` can be used in browser through module bundlers like [Browserify](https://github.com/substack/node-browserify) and [Webpack](https://github.com/webpack/webpack) or by including the precompiled bundle present in `build/` folder.
80
81 #### Module bundlers
82 ```html
83 <!-- index.html -->
84 <html>
85   <body>
86     <canvas id="canvas"></canvas>
87     <script src="bundle.js"></script>
88   </body>
89 </html>
90 ```
91
92 ```javascript
93 // index.js -> bundle.js
94 var QRCode = require('qrcode')
95 var canvas = document.getElementById('canvas')
96
97 QRCode.toCanvas(canvas, 'sample text', function (error) {
98   if (error) console.error(error)
99   console.log('success!');
100 })
101 ```
102
103 #### Precompiled bundle
104 ```html
105 <canvas id="canvas"></canvas>
106
107 <script src="/build/qrcode.min.js"></script>
108 <script>
109   QRCode.toCanvas(document.getElementById('canvas'), 'sample text', function (error) {
110     if (error) console.error(error)
111     console.log('success!');
112   })
113 </script>
114 ```
115
116 If you install through `npm`, precompiled files will be available in `node_modules/qrcode/build/` folder.<br>
117
118 ### NodeJS
119 Require the module `qrcode`
120
121 ```javascript
122 var QRCode = require('qrcode')
123
124 QRCode.toDataURL('I am a pony!', function (err, url) {
125   console.log(url)
126 })
127 ```
128
129 render a qrcode for the terminal
130 ```js
131 var QRCode = require('qrcode')
132
133 QRCode.toString('I am a pony!',{type:'terminal'}, function (err, url) {
134   console.log(url)
135 })
136 ```
137
138 ### ES6/ES7
139 Promises and Async/Await can be used in place of callback function.
140
141 ```javascript
142 import QRCode from 'qrcode'
143
144 // With promises
145 QRCode.toDataURL('I am a pony!')
146   .then(url => {
147     console.log(url)
148   })
149   .catch(err => {
150     console.error(err)
151   })
152
153 // With async/await
154 const generateQR = async text => {
155   try {
156     console.log(await QRCode.toDataURL(text))
157   } catch (err) {
158     console.error(err)
159   }
160 }
161 ```
162
163 ## Error correction level
164 Error correction capability allows to successfully scan a QR Code even if the symbol is dirty or damaged.
165 Four levels are available to choose according to the operating environment.
166
167 Higher levels offer a better error resistance but reduce the symbol's capacity.<br>
168 If the chances that the QR Code symbol may be corrupted are low (for example if it is showed through a monitor)
169 is possible to safely use a low error level such as `Low` or `Medium`.
170
171 Possible levels are shown below:
172
173 | Level            | Error resistance |
174 |------------------|:----------------:|
175 | **L** (Low)      | **~7%**          |
176 | **M** (Medium)   | **~15%**         |
177 | **Q** (Quartile) | **~25%**         |
178 | **H** (High)     | **~30%**         |
179
180 The percentage indicates the maximum amount of damaged surface after which the symbol becomes unreadable.
181
182 Error level can be set through `options.errorCorrectionLevel` property.<br>
183 If not specified, the default value is `M`.
184
185 ```javascript
186 QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
187   console.log(url)
188 })
189 ```
190
191 ## QR Code capacity
192 Capacity depends on symbol version and error correction level. Also encoding modes may influence the amount of storable data.
193
194 The QR Code versions range from version **1** to version **40**.<br>
195 Each version has a different number of modules (black and white dots), which define the symbol's size.
196 For version 1 they are `21x21`, for version 2 `25x25` e so on.
197 Higher is the version, more are the storable data, and of course bigger will be the QR Code symbol.
198
199 The table below shows the maximum number of storable characters in each encoding mode and for each error correction level.
200
201 | Mode         | L    | M    | Q    | H    |
202 |--------------|------|------|------|------|
203 | Numeric      | 7089 | 5596 | 3993 | 3057 |
204 | Alphanumeric | 4296 | 3391 | 2420 | 1852 |
205 | Byte         | 2953 | 2331 | 1663 | 1273 |
206 | Kanji        | 1817 | 1435 | 1024 | 784  |
207
208 **Note:** Maximum characters number can be different when using [Mixed modes](#mixed-modes).
209
210 QR Code version can be set through `options.version` property.<br>
211 If no version is specified, the more suitable value will be used. Unless a specific version is required, this option is not needed.
212
213 ```javascript
214 QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
215   console.log(url)
216 })
217 ```
218
219 ## Encoding modes
220 Modes can be used to encode a string in a more efficient way.<br>
221 A mode may be more suitable than others depending on the string content.
222 A list of supported modes are shown in the table below:
223
224 | Mode         | Characters                                                | Compression                               |
225 |--------------|-----------------------------------------------------------|-------------------------------------------|
226 | Numeric      | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9                              | 3 characters are represented by 10 bits   |
227 | Alphanumeric | 0–9, A–Z (upper-case only), space, $, %, *, +, -, ., /, : | 2 characters are represented by 11 bits   |
228 | Kanji        | Characters from the Shift JIS system based on JIS X 0208  | 2 kanji are represented by 13 bits        |
229 | Byte         | Characters from the ISO/IEC 8859-1 character set          | Each characters are represented by 8 bits |
230
231 Choose the right mode may be tricky if the input text is unknown.<br>
232 In these cases **Byte** mode is the best choice since all characters can be encoded with it. (See [Multibyte characters](#multibyte-characters))<br>
233 However, if the QR Code reader supports mixed modes, using [Auto mode](#auto-mode) may produce better results.
234
235 ### Mixed modes
236 Mixed modes are also possible. A QR code can be generated from a series of segments having different encoding modes to optimize the data compression.<br>
237 However, switching from a mode to another has a cost which may lead to a worst result if it's not taken into account.
238 See [Manual mode](#manual-mode) for an example of how to specify segments with different encoding modes.
239
240 ### Auto mode
241 By **default**, automatic mode selection is used.<br>
242 The input string is automatically splitted in various segments optimized to produce the shortest possible bitstream using mixed modes.<br>
243 This is the preferred way to generate the QR Code.
244
245 For example, the string **ABCDE12345678?A1A** will be splitted in 3 segments with the following modes:
246
247 | Segment  | Mode         |
248 |----------|--------------|
249 | ABCDE    | Alphanumeric |
250 | 12345678 | Numeric      |
251 | ?A1A     | Byte         |
252
253 Any other combinations of segments and modes will result in a longer bitstream.<br>
254 If you need to keep the QR Code size small, this mode will produce the best results.
255
256 ### Manual mode
257 If auto mode doesn't work for you or you have specific needs, is also possible to manually specify each segment with the relative mode.
258 In this way no segment optimizations will be applied under the hood.<br>
259 Segments list can be passed as an array of object:
260
261 ```javascript
262   var QRCode = require('qrcode')
263
264   var segs = [
265     { data: 'ABCDEFG', mode: 'alphanumeric' },
266     { data: '0123456', mode: 'numeric' }
267   ]
268
269   QRCode.toDataURL(segs, function (err, url) {
270     console.log(url)
271   })
272 ```
273
274 ### Kanji mode
275 With kanji mode is possible to encode characters from the Shift JIS system in an optimized way.<br>
276 Unfortunately, there isn't a way to calculate a Shifted JIS values from, for example, a character encoded in UTF-8, for this reason a conversion table from the input characters to the SJIS values is needed.<br>
277 This table is not included by default in the bundle to keep the size as small as possible.
278
279 If your application requires kanji support, you will need to pass a function that will take care of converting the input characters to appropriate values.
280
281 An helper method is provided by the lib through an optional file that you can include as shown in the example below.
282
283 **Note:** Support for Kanji mode is only needed if you want to benefit of the data compression, otherwise is still possible to encode kanji using Byte mode (See [Multibyte characters](#multibyte-characters)).
284
285 ```javascript
286   var QRCode = require('qrcode')
287   var toSJIS = require('qrcode/helper/to-sjis')
288
289   QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
290     console.log(url)
291   })
292 ```
293
294 With precompiled bundle:
295
296 ```html
297 <canvas id="canvas"></canvas>
298
299 <script src="/build/qrcode.min.js"></script>
300 <script src="/build/qrcode.tosjis.min.js"></script>
301 <script>
302   QRCode.toCanvas(document.getElementById('canvas'),
303     'sample text', { toSJISFunc: QRCode.toSJIS }, function (error) {
304     if (error) console.error(error)
305     console.log('success!')
306   })
307 </script>
308 ```
309
310 ## Binary data
311 QR Codes can hold arbitrary byte-based binary data. If you attempt to create a binary QR Code by first converting the data to a JavaScript string, it will fail to encode propery because string encoding adds additional bytes. Instead, you must pass a [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) or compatible array, or a Node [Buffer](https://nodejs.org/api/buffer.html), as follows:
312
313 ```javascript
314 // Regular array example
315 // WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
316 const QRCode = require('qrcode')
317 QRCode.toFile(
318   'foo.png',
319   [{ data: [253,254,255], mode: 'byte' }],
320   ...options...,
321   ...callback...
322 )
323 ```
324
325 ```javascript
326 // Uint8ClampedArray example
327 const QRCode = require('qrcode')
328
329 QRCode.toFile(
330   'foo.png',
331   [{ data: new Uint8ClampedArray([253,254,255]), mode: 'byte' }],
332   ...options...,
333   ...callback...
334 )
335 ```
336
337 ```javascript
338 // Node Buffer example
339 // WARNING: Element values will be clamped to 0-255 even if your data contains higher values.
340 const QRCode = require('qrcode')
341
342 QRCode.toFile(
343   'foo.png',
344   [{ data: Buffer.from([253,254,255]), mode: 'byte' }],
345   ...options...,
346   ...callback...
347 )
348 ```
349
350 TypeScript users: if you are using [@types/qrcode](https://www.npmjs.com/package/@types/qrcode), you will need to add a `// @ts-ignore` above the data segment because it expects `data: string`. 
351
352 ## Multibyte characters
353 Support for multibyte characters isn't present in the initial QR Code standard, but is possible to encode UTF-8 characters in Byte mode.
354
355 QR Codes provide a way to specify a different type of character set through ECI (Extended Channel Interpretation), but it's not fully implemented in this lib yet.
356
357 Most QR Code readers, however, are able to recognize multibyte characters even without ECI.
358
359 Note that a single Kanji/Kana or Emoji can take up to 4 bytes.
360
361 ## API
362 Browser:
363 - [create()](#createtext-options)
364 - [toCanvas()](#tocanvascanvaselement-text-options-cberror)
365 - [toDataURL()](#todataurltext-options-cberror-url)
366 - [toString()](#tostringtext-options-cberror-string)
367
368 Server:
369 - [create()](#createtext-options)
370 - [toCanvas()](#tocanvascanvas-text-options-cberror)
371 - [toDataURL()](#todataurltext-options-cberror-url-1)
372 - [toString()](#tostringtext-options-cberror-string-1)
373 - [toFile()](#tofilepath-text-options-cberror)
374 - [toFileStream()](#tofilestreamstream-text-options)
375
376 ### Browser API
377 #### `create(text, [options])`
378 Creates QR Code symbol and returns a qrcode object.
379
380 ##### `text`
381 Type: `String|Array`
382
383 Text to encode or a list of objects describing segments.
384
385 ##### `options`
386 See [QR Code options](#qr-code-options).
387
388 ##### `returns`
389 Type: `Object`
390
391 ```javascript
392 // QRCode object
393 {
394   modules,              // Bitmatrix class with modules data
395   version,              // Calculated QR Code version
396   errorCorrectionLevel, // Error Correction Level
397   maskPattern,          // Calculated Mask pattern
398   segments              // Generated segments
399 }
400 ```
401
402 <br>
403
404 #### `toCanvas(canvasElement, text, [options], [cb(error)])`
405 #### `toCanvas(text, [options], [cb(error, canvas)])`
406 Draws qr code symbol to canvas.<br>
407 If `canvasElement` is omitted a new canvas is returned.
408
409 ##### `canvasElement`
410 Type: `DOMElement`
411
412 Canvas where to draw QR Code.
413
414 ##### `text`
415 Type: `String|Array`
416
417 Text to encode or a list of objects describing segments.
418
419 ##### `options`
420 See [Options](#options).
421
422 ##### `cb`
423 Type: `Function`
424
425 Callback function called on finish.
426
427 ##### Example
428 ```javascript
429 QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) {
430   if (err) throw err
431
432   var container = document.getElementById('container')
433   container.appendChild(canvas)
434 })
435 ```
436
437 <br>
438
439 #### `toDataURL(text, [options], [cb(error, url)])`
440 #### `toDataURL(canvasElement, text, [options], [cb(error, url)])`
441 Returns a Data URI containing a representation of the QR Code image.<br>
442 If provided, `canvasElement` will be used as canvas to generate the data URI.
443
444 ##### `canvasElement`
445 Type: `DOMElement`
446
447 Canvas where to draw QR Code.
448
449 ##### `text`
450 Type: `String|Array`
451
452 Text to encode or a list of objects describing segments.
453
454 ##### `options`
455 - ###### `type`
456   Type: `String`<br>
457   Default: `image/png`
458
459   Data URI format.<br>
460   Possible values are: `image/png`, `image/jpeg`, `image/webp`.<br>
461
462 - ###### `rendererOpts.quality`
463   Type: `Number`<br>
464   Default: `0.92`
465
466   A Number between `0` and `1` indicating image quality if the requested type is `image/jpeg` or `image/webp`.
467
468 See [Options](#options) for other settings.
469
470 ##### `cb`
471 Type: `Function`
472
473 Callback function called on finish.
474
475 ##### Example
476 ```javascript
477 var opts = {
478   errorCorrectionLevel: 'H',
479   type: 'image/jpeg',
480   quality: 0.3,
481   margin: 1,
482   color: {
483     dark:"#010599FF",
484     light:"#FFBF60FF"
485   }
486 }
487
488 QRCode.toDataURL('text', opts, function (err, url) {
489   if (err) throw err
490
491   var img = document.getElementById('image')
492   img.src = url
493 })
494 ```
495 <br>
496
497 #### `toString(text, [options], [cb(error, string)])`
498
499 Returns a string representation of the QR Code.<br>
500
501
502 ##### `text`
503 Type: `String|Array`
504
505 Text to encode or a list of objects describing segments.
506
507 ##### `options`
508 - ###### `type`
509   Type: `String`<br>
510   Default: `utf8`
511
512   Output format.<br>
513   Possible values are: `terminal`,`utf8`, and `svg`.
514
515 See [Options](#options) for other settings.
516
517 ##### `cb`
518 Type: `Function`
519
520 Callback function called on finish.
521
522 ##### Example
523 ```javascript
524 QRCode.toString('http://www.google.com', function (err, string) {
525   if (err) throw err
526   console.log(string)
527 })
528 ```
529
530 <br>
531
532
533 ### Server API
534 #### `create(text, [options])`
535 See [create](#createtext-options).
536
537 <br>
538
539 #### `toCanvas(canvas, text, [options], [cb(error)])`
540 Draws qr code symbol to [node canvas](https://github.com/Automattic/node-canvas).
541
542 ##### `text`
543 Type: `String|Array`
544
545 Text to encode or a list of objects describing segments.
546
547 ##### `options`
548 See [Options](#options).
549
550 ##### `cb`
551 Type: `Function`
552
553 Callback function called on finish.
554
555 <br>
556
557 #### `toDataURL(text, [options], [cb(error, url)])`
558 Returns a Data URI containing a representation of the QR Code image.<br>
559 Only works with `image/png` type for now.
560
561 ##### `text`
562 Type: `String|Array`
563
564 Text to encode or a list of objects describing segments.
565
566 ##### `options`
567 See [Options](#options) for other settings.
568
569 ##### `cb`
570 Type: `Function`
571
572 Callback function called on finish.
573
574 <br>
575
576 #### `toString(text, [options], [cb(error, string)])`
577 Returns a string representation of the QR Code.<br>
578 If choosen output format is `svg` it will returns a string containing xml code.
579
580 ##### `text`
581 Type: `String|Array`
582
583 Text to encode or a list of objects describing segments.
584
585 ##### `options`
586 - ###### `type`
587   Type: `String`<br>
588   Default: `utf8`
589
590   Output format.<br>
591   Possible values are: `utf8`, `svg`, `terminal`.
592
593 See [Options](#options) for other settings.
594
595 ##### `cb`
596 Type: `Function`
597
598 Callback function called on finish.
599
600 ##### Example
601 ```javascript
602 QRCode.toString('http://www.google.com', function (err, string) {
603   if (err) throw err
604   console.log(string)
605 })
606 ```
607
608 <br>
609
610 #### `toFile(path, text, [options], [cb(error)])`
611 Saves QR Code to image file.<br>
612 If `options.type` is not specified, the format will be guessed from file extension.<br>
613 Recognized extensions are `png`, `svg`, `txt`.
614
615 ##### `path`
616 Type: `String`
617
618 Path where to save the file.
619
620 ##### `text`
621 Type: `String|Array`
622
623 Text to encode or a list of objects describing segments.
624
625 ##### `options`
626 - ###### `type`
627   Type: `String`<br>
628   Default: `png`
629
630   Output format.<br>
631   Possible values are: `png`, `svg`, `utf8`.
632
633 - ###### `rendererOpts.deflateLevel` **(png only)**
634   Type: `Number`<br>
635   Default: `9`
636
637   Compression level for deflate.
638
639 - ###### `rendererOpts.deflateStrategy` **(png only)**
640   Type: `Number`<br>
641   Default: `3`
642
643   Compression strategy for deflate.
644
645 See [Options](#options) for other settings.
646
647 ##### `cb`
648 Type: `Function`
649
650 Callback function called on finish.
651
652 ##### Example
653 ```javascript
654 QRCode.toFile('path/to/filename.png', 'Some text', {
655   color: {
656     dark: '#00F',  // Blue dots
657     light: '#0000' // Transparent background
658   }
659 }, function (err) {
660   if (err) throw err
661   console.log('done')
662 })
663 ```
664
665 <br>
666
667 #### `toFileStream(stream, text, [options])`
668 Writes QR Code image to stream. Only works with `png` format for now.
669
670 ##### `stream`
671 Type: `stream.Writable`
672
673 Node stream.
674
675 ##### `text`
676 Type: `String|Array`
677
678 Text to encode or a list of objects describing segments.
679
680 ##### `options`
681 See [Options](#options).
682
683 <br>
684
685 ### Options
686
687 #### QR Code options
688 ##### `version`
689   Type: `Number`<br>
690
691   QR Code version. If not specified the more suitable value will be calculated.
692
693 ##### `errorCorrectionLevel`
694   Type: `String`<br>
695   Default: `M`
696
697   Error correction level.<br>
698   Possible values are `low, medium, quartile, high` or `L, M, Q, H`.
699
700 ##### `maskPattern`
701   Type: `Number`<br>
702
703   Mask pattern used to mask the symbol.<br>
704   Possible values are `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`.<br>
705   If not specified the more suitable value will be calculated.
706
707 ##### `toSJISFunc`
708   Type: `Function`<br>
709
710   Helper function used internally to convert a kanji to its Shift JIS value.<br>
711   Provide this function if you need support for Kanji mode.
712
713 #### Renderers options
714 ##### `margin`
715   Type: `Number`<br>
716   Default: `4`
717
718   Define how much wide the quiet zone should be.
719
720 ##### `scale`
721   Type: `Number`<br>
722   Default: `4`
723
724   Scale factor. A value of `1` means 1px per modules (black dots).
725
726 ##### `width`
727   Type: `Number`<br>
728
729   Forces a specific width for the output image.<br>
730   If width is too small to contain the qr symbol, this option will be ignored.<br>
731   Takes precedence over `scale`.
732
733 ##### `color.dark`
734 Type: `String`<br>
735 Default: `#000000ff`
736
737 Color of dark module. Value must be in hex format (RGBA).<br>
738 Note: dark color should always be darker than `color.light`.
739
740 ##### `color.light`
741 Type: `String`<br>
742 Default: `#ffffffff`
743
744 Color of light module. Value must be in hex format (RGBA).<br>
745
746 <br>
747
748 ## GS1 QR Codes
749 There was a real good discussion here about them. but in short any qrcode generator will make gs1 compatible qrcodes, but what defines a gs1 qrcode is a header with metadata that describes your gs1 information.
750
751 https://github.com/soldair/node-qrcode/issues/45
752
753
754 ## Credits
755 This lib is based on "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed.
756
757 ## License
758 [MIT](https://github.com/soldair/node-qrcode/blob/master/license)
759
760 The word "QR Code" is registered trademark of:<br>
761 DENSO WAVE INCORPORATED