__init__.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Michael Nooner
  3. # All rights reserved.
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are met:
  6. # * Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # * Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. # * Neither the name of the copyright holder nor the names of its
  12. # contributors may be used to endorse or promote products derived from
  13. # this software without specific prior written permission
  14. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. # ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  18. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. """This module is used to create QR Codes. It is designed to be as simple and
  25. as possible. It does this by using sane defaults and autodetection to make
  26. creating a QR Code very simple.
  27. It is recommended that you use the :func:`pyqrcode.create` function to build the
  28. QRCode object. This results in cleaner looking code.
  29. Examples:
  30. >>> import pyqrcode
  31. >>> import sys
  32. >>> url = pyqrcode.create('http://uca.edu')
  33. >>> url.svg(sys.stdout, scale=1)
  34. >>> url.svg('uca.svg', scale=4)
  35. >>> number = pyqrcode.create(123456789012345)
  36. >>> number.png('big-number.png')
  37. """
  38. #Imports required for 2.7 support
  39. from __future__ import absolute_import, division, print_function, with_statement, unicode_literals
  40. import pyqrcode.tables
  41. import pyqrcode.builder as builder
  42. try:
  43. str = unicode # Python 2
  44. except NameError:
  45. pass
  46. def create(content, error='H', version=None, mode=None, encoding=None):
  47. """When creating a QR code only the content to be encoded is required,
  48. all the other properties of the code will be guessed based on the
  49. contents given. This function will return a :class:`QRCode` object.
  50. Unless you are familiar with QR code's inner workings
  51. it is recommended that you just specify the *content* and nothing else.
  52. However, there are cases where you may want to specify the various
  53. properties of the created code manually, this is what the other
  54. parameters do. Below, you will find a lengthy explanation of what
  55. each parameter is for. Note, the parameter names and values are taken
  56. directly from the standards. You may need to familiarize yourself
  57. with the terminology of QR codes for the names and their values to
  58. make sense.
  59. The *error* parameter sets the error correction level of the code. There
  60. are four levels defined by the standard. The first is level 'L' which
  61. allows for 7% of the code to be corrected. Second, is level 'M' which
  62. allows for 15% of the code to be corrected. Next, is level 'Q' which
  63. is the most common choice for error correction, it allow 25% of the
  64. code to be corrected. Finally, there is the highest level 'H' which
  65. allows for 30% of the code to be corrected. There are several ways to
  66. specify this parameter, you can use an upper or lower case letter,
  67. a float corresponding to the percentage of correction, or a string
  68. containing the percentage. See tables.modes for all the possible
  69. values. By default this parameter is set to 'H' which is the highest
  70. possible error correction, but it has the smallest available data
  71. capacity.
  72. The *version* parameter specifies the size and data capacity of the
  73. code. Versions are any integer between 1 and 40. Where version 1 is
  74. the smallest QR code, and version 40 is the largest. If this parameter
  75. is left unspecified, then the contents and error correction level will
  76. be used to guess the smallest possible QR code version that the
  77. content will fit inside of. You may want to specify this parameter
  78. for consistency when generating several QR codes with varying amounts
  79. of data. That way all of the generated codes would have the same size.
  80. The *mode* parameter specifies how the contents will be encoded. By
  81. default, the best possible mode for the contents is guessed. There
  82. are four possible modes. First, is 'numeric' which is
  83. used to encode integer numbers. Next, is 'alphanumeric' which is
  84. used to encode some ASCII characters. This mode uses only a limited
  85. set of characters. Most problematic is that it can only use upper case
  86. English characters, consequently, the content parameter will be
  87. subjected to str.upper() before encoding. See tables.ascii_codes for
  88. a complete list of available characters. The is 'kanji' mode can be
  89. used for Japanese characters, but only those that can be understood
  90. via the shift-jis string encoding. Finally, we then have 'binary' mode
  91. which just encodes the bytes directly into the QR code (this encoding
  92. is the least efficient).
  93. The *encoding* parameter specifies how the content will be interpreted.
  94. This parameter only matters if the *content* is a string, unicode, or
  95. byte array type. This parameter must be a valid encoding string or None.
  96. t will be passed the *content*'s encode/decode methods.
  97. """
  98. return QRCode(content, error, version, mode, encoding)
  99. class QRCode:
  100. """This class represents a QR code. To use this class simply give the
  101. constructor a string representing the data to be encoded, it will then
  102. build a code in memory. You can then save it in various formats. Note,
  103. codes can be written out as PNG files but this requires the PyPNG module.
  104. You can find the PyPNG module at http://packages.python.org/pypng/.
  105. Examples:
  106. >>> from pyqrcode import QRCode
  107. >>> import sys
  108. >>> url = QRCode('http://uca.edu')
  109. >>> url.svg(sys.stdout, scale=1)
  110. >>> url.svg('uca.svg', scale=4)
  111. >>> number = QRCode(123456789012345)
  112. >>> number.png('big-number.png')
  113. .. note::
  114. For what all of the parameters do, see the :func:`pyqrcode.create`
  115. function.
  116. """
  117. def __init__(self, content, error='H', version=None, mode=None,
  118. encoding='iso-8859-1'):
  119. #Guess the mode of the code, this will also be used for
  120. #error checking
  121. guessed_content_type, encoding = self._detect_content_type(content, encoding)
  122. if encoding is None:
  123. encoding = 'iso-8859-1'
  124. #Store the encoding for use later
  125. if guessed_content_type == 'kanji':
  126. self.encoding = 'shiftjis'
  127. else:
  128. self.encoding = encoding
  129. if version is not None:
  130. if 1 <= version <= 40:
  131. self.version = version
  132. else:
  133. raise ValueError("Illegal version {0}, version must be between "
  134. "1 and 40.".format(version))
  135. #Decode a 'byte array' contents into a string format
  136. if isinstance(content, bytes):
  137. self.data = content.decode(encoding)
  138. #Give a string an encoding
  139. elif hasattr(content, 'encode'):
  140. self.data = content.encode(self.encoding)
  141. #The contents are not a byte array or string, so
  142. #try naively converting to a string representation.
  143. else:
  144. self.data = str(content) # str == unicode in Py 2.x, see file head
  145. #Force a passed in mode to be lowercase
  146. if hasattr(mode, 'lower'):
  147. mode = mode.lower()
  148. #Check that the mode parameter is compatible with the contents
  149. if mode is None:
  150. #Use the guessed mode
  151. self.mode = guessed_content_type
  152. self.mode_num = tables.modes[self.mode]
  153. elif mode not in tables.modes.keys():
  154. #Unknown mode
  155. raise ValueError('{0} is not a valid mode.'.format(mode))
  156. elif guessed_content_type == 'binary' and \
  157. tables.modes[mode] != tables.modes['binary']:
  158. #Binary is only guessed as a last resort, if the
  159. #passed in mode is not binary the data won't encode
  160. raise ValueError('The content provided cannot be encoded with '
  161. 'the mode {}, it can only be encoded as '
  162. 'binary.'.format(mode))
  163. elif tables.modes[mode] == tables.modes['numeric'] and \
  164. guessed_content_type != 'numeric':
  165. #If numeric encoding is requested make sure the data can
  166. #be encoded in that format
  167. raise ValueError('The content cannot be encoded as numeric.')
  168. elif tables.modes[mode] == tables.modes['kanji'] and \
  169. guessed_content_type != 'kanji':
  170. raise ValueError('The content cannot be encoded as kanji.')
  171. else:
  172. #The data should encode with the passed in mode
  173. self.mode = mode
  174. self.mode_num = tables.modes[self.mode]
  175. #Check that the user passed in a valid error level
  176. if error in tables.error_level.keys():
  177. self.error = tables.error_level[error]
  178. else:
  179. raise ValueError('{0} is not a valid error '
  180. 'level.'.format(error))
  181. #Guess the "best" version
  182. self.version = self._pick_best_fit(self.data)
  183. #If the user supplied a version, then check that it has
  184. #sufficient data capacity for the contents passed in
  185. if version:
  186. if version >= self.version:
  187. self.version = version
  188. else:
  189. raise ValueError('The data will not fit inside a version {} '
  190. 'code with the given encoding and error '
  191. 'level (the code must be at least a '
  192. 'version {}).'.format(version, self.version))
  193. #Build the QR code
  194. self.builder = builder.QRCodeBuilder(data=self.data,
  195. version=self.version,
  196. mode=self.mode,
  197. error=self.error)
  198. #Save the code for easier reference
  199. self.code = self.builder.code
  200. def __str__(self):
  201. return repr(self)
  202. def __unicode__(self):
  203. return self.__repr__()
  204. def __repr__(self):
  205. return "QRCode(content={0}, error='{1}', version={2}, mode='{3}')" \
  206. .format(repr(self.data), self.error, self.version, self.mode)
  207. def _detect_content_type(self, content, encoding):
  208. """This method tries to auto-detect the type of the data. It first
  209. tries to see if the data is a valid integer, in which case it returns
  210. numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
  211. Codes use a special table with very limited range of ASCII characters.
  212. The code's data is tested to make sure it fits inside this limited
  213. range. If all else fails, the data is determined to be of type
  214. 'binary.'
  215. Returns a tuple containing the detected mode and encoding.
  216. Note, encoding ECI is not yet implemented.
  217. """
  218. def two_bytes(c):
  219. """Output two byte character code as a single integer."""
  220. def next_byte(b):
  221. """Make sure that character code is an int. Python 2 and
  222. 3 compatibility.
  223. """
  224. if not isinstance(b, int):
  225. return ord(b)
  226. else:
  227. return b
  228. #Go through the data by looping to every other character
  229. for i in range(0, len(c), 2):
  230. yield (next_byte(c[i]) << 8) | next_byte(c[i+1])
  231. #See if the data is a number
  232. try:
  233. if str(content).isdigit():
  234. return 'numeric', encoding
  235. except (TypeError, UnicodeError):
  236. pass
  237. #See if that data is alphanumeric based on the standards
  238. #special ASCII table
  239. valid_characters = ''.join(tables.ascii_codes.keys())
  240. #Force the characters into a byte array
  241. valid_characters = valid_characters.encode('ASCII')
  242. try:
  243. if isinstance(content, bytes):
  244. c = content.decode('ASCII')
  245. else:
  246. c = str(content).encode('ASCII')
  247. if all(map(lambda x: x in valid_characters, c)):
  248. return 'alphanumeric', 'ASCII'
  249. #This occurs if the content does not contain ASCII characters.
  250. #Since the whole point of the if statement is to look for ASCII
  251. #characters, the resulting mode should not be alphanumeric.
  252. #Hence, this is not an error.
  253. except TypeError:
  254. pass
  255. except UnicodeError:
  256. pass
  257. try:
  258. if isinstance(content, bytes):
  259. if encoding is None:
  260. encoding = 'shiftjis'
  261. c = content.decode(encoding).encode('shiftjis')
  262. else:
  263. c = content.encode('shiftjis')
  264. #All kanji characters must be two bytes long, make sure the
  265. #string length is not odd.
  266. if len(c) % 2 != 0:
  267. return 'binary', encoding
  268. #Make sure the characters are actually in range.
  269. for asint in two_bytes(c):
  270. #Shift the two byte value as indicated by the standard
  271. if not (0x8140 <= asint <= 0x9FFC or
  272. 0xE040 <= asint <= 0xEBBF):
  273. return 'binary', encoding
  274. return 'kanji', encoding
  275. except UnicodeError:
  276. #This occurs if the content does not contain Shift JIS kanji
  277. #characters. Hence, the resulting mode should not be kanji.
  278. #This is not an error.
  279. pass
  280. #All of the other attempts failed. The content can only be binary.
  281. return 'binary', encoding
  282. def _pick_best_fit(self, content):
  283. """This method return the smallest possible QR code version number
  284. that will fit the specified data with the given error level.
  285. """
  286. import math
  287. for version in range(1, 41):
  288. #Get the maximum possible capacity
  289. capacity = tables.data_capacity[version][self.error][self.mode_num]
  290. #Check the capacity
  291. #Kanji's count in the table is "characters" which are two bytes
  292. if (self.mode_num == tables.modes['kanji'] and
  293. capacity >= math.ceil(len(content) / 2)):
  294. return version
  295. if capacity >= len(content):
  296. return version
  297. raise ValueError('The data will not fit in any QR code version '
  298. 'with the given encoding and error level.')
  299. def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
  300. background=(255, 255, 255, 255), quiet_zone=4):
  301. """Displays this QR code.
  302. This method is mainly intended for debugging purposes.
  303. This method saves the output of the :py:meth:`png` method (with a default
  304. scaling factor of 10) to a temporary file and opens it with the
  305. standard PNG viewer application or within the standard webbrowser. The
  306. temporary file is deleted afterwards.
  307. If this method does not show any result, try to increase the `wait`
  308. parameter. This parameter specifies the time in seconds to wait till
  309. the temporary file is deleted. Note, that this method does not return
  310. until the provided amount of seconds (default: 1.2) has passed.
  311. The other parameters are simply passed on to the `png` method.
  312. """
  313. import os
  314. import time
  315. import tempfile
  316. import webbrowser
  317. try: # Python 2
  318. from urlparse import urljoin
  319. from urllib import pathname2url
  320. except ImportError: # Python 3
  321. from urllib.parse import urljoin
  322. from urllib.request import pathname2url
  323. f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
  324. self.png(f, scale=scale, module_color=module_color,
  325. background=background, quiet_zone=quiet_zone)
  326. f.close()
  327. webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
  328. time.sleep(wait)
  329. os.unlink(f.name)
  330. def get_png_size(self, scale=1, quiet_zone=4):
  331. """This is method helps users determine what *scale* to use when
  332. creating a PNG of this QR code. It is meant mostly to be used in the
  333. console to help the user determine the pixel size of the code
  334. using various scales.
  335. This method will return an integer representing the width and height of
  336. the QR code in pixels, as if it was drawn using the given *scale*.
  337. Because QR codes are square, the number represents both the width
  338. and height dimensions.
  339. The *quiet_zone* parameter sets how wide the quiet zone around the code
  340. should be. According to the standard this should be 4 modules. It is
  341. left settable because such a wide quiet zone is unnecessary in many
  342. applications where the QR code is not being printed.
  343. Example:
  344. >>> code = pyqrcode.QRCode("I don't like spam!")
  345. >>> print(code.get_png_size(1))
  346. 31
  347. >>> print(code.get_png_size(5))
  348. 155
  349. """
  350. return builder._get_png_size(self.version, scale, quiet_zone)
  351. def png(self, file, scale=1, module_color=(0, 0, 0, 255),
  352. background=(255, 255, 255, 255), quiet_zone=4):
  353. """This method writes the QR code out as an PNG image. The resulting
  354. PNG has a bit depth of 1. The file parameter is used to specify where
  355. to write the image to. It can either be an writable stream or a
  356. file path.
  357. .. note::
  358. This method depends on the pypng module to actually create the
  359. PNG file.
  360. This method will write the given *file* out as a PNG file. The file
  361. can be either a string file path, or a writable stream. The file
  362. will not be automatically closed if a stream is given.
  363. The *scale* parameter sets how large to draw a single module. By
  364. default one pixel is used to draw a single module. This may make the
  365. code too small to be read efficiently. Increasing the scale will make
  366. the code larger. Only integer scales are usable. This method will
  367. attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
  368. and '3' will become 3). You can use the :py:meth:`get_png_size` method
  369. to calculate the actual pixel size of the resulting PNG image.
  370. The *module_color* parameter sets what color to use for the encoded
  371. modules (the black part on most QR codes). The *background* parameter
  372. sets what color to use for the background (the white part on most
  373. QR codes). If either parameter is set, then both must be
  374. set or a ValueError is raised. Colors should be specified as either
  375. a list or a tuple of length 3 or 4. The components of the list must
  376. be integers between 0 and 255. The first three member give the RGB
  377. color. The fourth member gives the alpha component, where 0 is
  378. transparent and 255 is opaque. Note, many color
  379. combinations are unreadable by scanners, so be judicious.
  380. The *quiet_zone* parameter sets how wide the quiet zone around the code
  381. should be. According to the standard this should be 4 modules. It is
  382. left settable because such a wide quiet zone is unnecessary in many
  383. applications where the QR code is not being printed.
  384. Example:
  385. >>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
  386. >>> code.png('swallow.png', scale=5)
  387. >>> code.png('swallow.png', scale=5,
  388. module_color=(0x66, 0x33, 0x0), #Dark brown
  389. background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white
  390. """
  391. builder._png(self.code, self.version, file, scale,
  392. module_color, background, quiet_zone)
  393. def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
  394. background=(255, 255, 255, 255), quiet_zone=4):
  395. """This method uses the png render and returns the PNG image encoded as
  396. base64 string. This can be useful for creating dynamic PNG images for
  397. web development, since no file needs to be created.
  398. Example:
  399. >>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
  400. >>> image_as_str = code.png_as_base64_str(scale=5)
  401. >>> html_img = '<img src="data:image/png;base64,{}">'.format(image_as_str)
  402. The parameters are passed directly to the :py:meth:`png` method. Refer
  403. to that method's documentation for the meaning behind the parameters.
  404. .. note::
  405. This method depends on the pypng module to actually create the
  406. PNG image.
  407. """
  408. import io
  409. import base64
  410. with io.BytesIO() as virtual_file:
  411. self.png(file=virtual_file, scale=scale, module_color=module_color,
  412. background=background, quiet_zone=quiet_zone)
  413. image_as_str = base64.b64encode(virtual_file.getvalue()).decode("ascii")
  414. return image_as_str
  415. def xbm(self, scale=1, quiet_zone=4):
  416. """Returns a string representing an XBM image of the QR code.
  417. The XBM format is a black and white image format that looks like a
  418. C header file.
  419. Because displaying QR codes in Tkinter is the
  420. primary use case for this renderer, this method does not take a file
  421. parameter. Instead it retuns the rendered QR code data as a string.
  422. Example of using this renderer with Tkinter:
  423. >>> import pyqrcode
  424. >>> import tkinter
  425. >>> code = pyqrcode.create('Knights who say ni!')
  426. >>> code_xbm = code.xbm(scale=5)
  427. >>>
  428. >>> top = tkinter.Tk()
  429. >>> code_bmp = tkinter.BitmapImage(data=code_xbm)
  430. >>> code_bmp.config(foreground="black")
  431. >>> code_bmp.config(background="white")
  432. >>> label = tkinter.Label(image=code_bmp)
  433. >>> label.pack()
  434. The *scale* parameter sets how large to draw a single module. By
  435. default one pixel is used to draw a single module. This may make the
  436. code too small to be read efficiently. Increasing the scale will make
  437. the code larger. Only integer scales are usable. This method will
  438. attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
  439. and '3' will become 3). You can use the :py:meth:`get_png_size` method
  440. to calculate the actual pixel size of this image when displayed.
  441. The *quiet_zone* parameter sets how wide the quiet zone around the code
  442. should be. According to the standard this should be 4 modules. It is
  443. left settable because such a wide quiet zone is unnecessary in many
  444. applications where the QR code is not being printed.
  445. """
  446. return builder._xbm(self.code, scale, quiet_zone)
  447. def svg(self, file, scale=1, module_color='#000', background=None,
  448. quiet_zone=4, xmldecl=True, svgns=True, title=None,
  449. svgclass='pyqrcode', lineclass='pyqrline', omithw=False,
  450. debug=False):
  451. """This method writes the QR code out as an SVG document. The
  452. code is drawn by drawing only the modules corresponding to a 1. They
  453. are drawn using a line, such that contiguous modules in a row
  454. are drawn with a single line.
  455. The *file* parameter is used to specify where to write the document
  456. to. It can either be a writable stream or a file path.
  457. The *scale* parameter sets how large to draw
  458. a single module. By default one pixel is used to draw a single
  459. module. This may make the code too small to be read efficiently.
  460. Increasing the scale will make the code larger. Unlike the png() method,
  461. this method will accept fractional scales (e.g. 2.5).
  462. Note, three things are done to make the code more appropriate for
  463. embedding in a HTML document. The "white" part of the code is actually
  464. transparent. The code itself has a class given by *svgclass* parameter.
  465. The path making up the QR code uses the class set using the *lineclass*.
  466. These should make the code easier to style using CSS.
  467. By default the output of this function is a complete SVG document. If
  468. only the code itself is desired, set the *xmldecl* to false. This will
  469. result in a fragment that contains only the "drawn" portion of the code.
  470. Likewise, you can set the *title* of the document. The SVG name space
  471. attribute can be suppressed by setting *svgns* to False.
  472. When True the *omithw* indicates if width and height attributes should
  473. be omitted. If these attributes are omitted, a ``viewBox`` attribute
  474. will be added to the document.
  475. You can also set the colors directly using the *module_color* and
  476. *background* parameters. The *module_color* parameter sets what color to
  477. use for the data modules (the black part on most QR codes). The
  478. *background* parameter sets what color to use for the background (the
  479. white part on most QR codes). The parameters can be set to any valid
  480. SVG or HTML color. If the background is set to None, then no background
  481. will be drawn, i.e. the background will be transparent. Note, many color
  482. combinations are unreadable by scanners, so be careful.
  483. The *quiet_zone* parameter sets how wide the quiet zone around the code
  484. should be. According to the standard this should be 4 modules. It is
  485. left settable because such a wide quiet zone is unnecessary in many
  486. applications where the QR code is not being printed.
  487. Example:
  488. >>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
  489. >>> code.svg('live-organ-transplants.svg', 3.6)
  490. >>> code.svg('live-organ-transplants.svg', scale=4,
  491. module_color='brown', background='0xFFFFFF')
  492. """
  493. builder._svg(self.code, self.version, file, scale=scale,
  494. module_color=module_color, background=background,
  495. quiet_zone=quiet_zone, xmldecl=xmldecl, svgns=svgns,
  496. title=title, svgclass=svgclass, lineclass=lineclass,
  497. omithw=omithw, debug=debug)
  498. def eps(self, file, scale=1, module_color=(0, 0, 0),
  499. background=None, quiet_zone=4):
  500. """This method writes the QR code out as an EPS document. The
  501. code is drawn by only writing the data modules corresponding to a 1.
  502. They are drawn using a line, such that contiguous modules in a row
  503. are drawn with a single line.
  504. The *file* parameter is used to specify where to write the document
  505. to. It can either be a writable (text) stream or a file path.
  506. The *scale* parameter sets how large to draw a single module. By
  507. default one point (1/72 inch) is used to draw a single module. This may
  508. make the code to small to be read efficiently. Increasing the scale
  509. will make the code larger. This method will accept fractional scales
  510. (e.g. 2.5).
  511. The *module_color* parameter sets the color of the data modules. The
  512. *background* parameter sets the background (page) color to use. They
  513. are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
  514. triple of integers, e.g. (128, 128, 128). The default *module_color* is
  515. black. The default *background* color is no background at all.
  516. The *quiet_zone* parameter sets how large to draw the border around
  517. the code. As per the standard, the default value is 4 modules.
  518. Examples:
  519. >>> qr = pyqrcode.create('Hello world')
  520. >>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
  521. >>> qr.eps('hello-world2.eps', background='#eee')
  522. >>> out = io.StringIO()
  523. >>> qr.eps(out, module_color=(.4, .4, .4))
  524. """
  525. builder._eps(self.code, self.version, file, scale, module_color,
  526. background, quiet_zone)
  527. def terminal(self, module_color='default', background='reverse',
  528. quiet_zone=4):
  529. """This method returns a string containing ASCII escape codes,
  530. such that if printed to a compatible terminal, it will display
  531. a vaild QR code. The code is printed using ASCII escape
  532. codes that alter the coloring of the background.
  533. The *module_color* parameter sets what color to
  534. use for the data modules (the black part on most QR codes).
  535. Likewise, the *background* parameter sets what color to use
  536. for the background (the white part on most QR codes).
  537. There are two options for colors. The first, and most widely
  538. supported, is to use the 8 or 16 color scheme. This scheme uses
  539. eight to sixteen named colors. The following colors are
  540. supported the most widely supported: black, red, green,
  541. yellow, blue, magenta, and cyan. There are an some additional
  542. named colors that are supported by most terminals: light gray,
  543. dark gray, light red, light green, light blue, light yellow,
  544. light magenta, light cyan, and white.
  545. There are two special named colors. The first is the
  546. "default" color. This color is the color the background of
  547. the terminal is set to. The next color is the "reverse"
  548. color. This is not really a color at all but a special
  549. property that will reverse the current color. These two colors
  550. are the default values for *module_color* and *background*
  551. respectively. These values should work on most terminals.
  552. Finally, there is one more way to specify the color. Some
  553. terminals support 256 colors. The actual colors displayed in the
  554. terminal is system dependent. This is the least transportable option.
  555. To use the 256 color scheme set *module_color* and/or
  556. *background* to a number between 0 and 256.
  557. The *quiet_zone* parameter sets how wide the quiet zone around the code
  558. should be. According to the standard this should be 4 modules. It is
  559. left settable because such a wide quiet zone is unnecessary in many
  560. applications.
  561. Example:
  562. >>> code = pyqrcode.create('Example')
  563. >>> text = code.terminal()
  564. >>> print(text)
  565. """
  566. return builder._terminal(self.code, module_color, background,
  567. quiet_zone)
  568. def text(self, quiet_zone=4):
  569. """This method returns a string based representation of the QR code.
  570. The data modules are represented by 1's and the background modules are
  571. represented by 0's. The main purpose of this method is to act a
  572. starting point for users to create their own renderers.
  573. The *quiet_zone* parameter sets how wide the quiet zone around the code
  574. should be. According to the standard this should be 4 modules. It is
  575. left settable because such a wide quiet zone is unnecessary in many
  576. applications.
  577. Example:
  578. >>> code = pyqrcode.create('Example')
  579. >>> text = code.text()
  580. >>> print(text)
  581. """
  582. return builder._text(self.code, quiet_zone)