|
3 | 3 | created as SVG objects. If Pillow is installed, the barcodes can also be
|
4 | 4 | rendered as images (all formats supported by Pillow).
|
5 | 5 | """
|
| 6 | +import os |
| 7 | +from typing import BinaryIO |
| 8 | +from typing import Dict |
| 9 | +from typing import Union |
| 10 | + |
6 | 11 | from barcode.codex import Code128
|
7 | 12 | from barcode.codex import Code39
|
8 | 13 | from barcode.codex import Gs1_128
|
@@ -76,15 +81,37 @@ def get_class(name):
|
76 | 81 |
|
77 | 82 |
|
78 | 83 | def generate(
|
79 |
| - name, code, writer=None, output=None, writer_options=None, text=None, |
| 84 | + name: str, |
| 85 | + code: str, |
| 86 | + writer=None, |
| 87 | + output: Union[str, os.PathLike, BinaryIO] = None, |
| 88 | + writer_options: Dict = None, |
| 89 | + text: str = None, |
80 | 90 | ):
|
81 |
| - writer_options = writer_options or {} |
82 |
| - barcode = get(name, code, writer, writer_options=writer_options) |
| 91 | + """Shortcut to generate a barcode in one line. |
| 92 | +
|
| 93 | + :param name: Name of the type of barcode to use. |
| 94 | + :param code: Data to encode into the barcode. |
| 95 | + :param writer: A writer to use (e.g.: ImageWriter or SVGWriter). |
| 96 | + :param output: Destination file-like or path-like where to save the generated |
| 97 | + barcode. |
| 98 | + :param writer_options: Options to pass on to the writer instance. |
| 99 | + :param text: Text to render under the barcode. |
| 100 | + """ |
| 101 | + from barcode.base import Barcode |
| 102 | + |
| 103 | + writer = writer or Barcode.default_writer() |
| 104 | + writer.set_options(writer_options or {}) |
| 105 | + |
| 106 | + barcode = get(name, code, writer) |
| 107 | + |
83 | 108 | if isinstance(output, str):
|
84 | 109 | fullname = barcode.save(output, writer_options, text)
|
85 | 110 | return fullname
|
86 |
| - else: |
| 111 | + elif output: |
87 | 112 | barcode.write(output, writer_options, text)
|
| 113 | + else: |
| 114 | + raise TypeError("'output' cannot be None") |
88 | 115 |
|
89 | 116 |
|
90 | 117 | get_barcode = get
|
|
0 commit comments