diff --git a/barcode/base.py b/barcode/base.py index e470c07..7b7b0fe 100755 --- a/barcode/base.py +++ b/barcode/base.py @@ -80,10 +80,7 @@ def write(self, fp, options=None, text=None): Text to render under the barcode. """ output = self.render(options, text) - if hasattr(output, "tostring"): - output.save(fp, format=self.writer.format) - else: - fp.write(output) + self.writer.write(output, fp) def render(self, writer_options=None, text=None): """Renders the barcode using `self.writer`. diff --git a/barcode/writer.py b/barcode/writer.py index 7beb190..5f4b1e6 100755 --- a/barcode/writer.py +++ b/barcode/writer.py @@ -1,6 +1,7 @@ import gzip import os import xml.dom +from typing.io import BinaryIO from barcode.version import version @@ -318,6 +319,13 @@ def save(self, filename, output): f.write(output) return _filename + def write(self, content, fp: BinaryIO): + """Write `content` into a file-like object. + + Content should be a barcode rendered by this writer. + """ + fp.write(content) + if Image is None: ImageWriter = None @@ -367,3 +375,10 @@ def save(self, filename, output): filename = "{}.{}".format(filename, self.format.lower()) output.save(filename, self.format.upper()) return filename + + def write(self, content, fp: BinaryIO): + """Write `content` into a file-like object. + + Content should be a barcode rendered by this writer. + """ + content.save(fp, format=self.format) diff --git a/tests/test_writers.py b/tests/test_writers.py new file mode 100644 index 0000000..2cccc02 --- /dev/null +++ b/tests/test_writers.py @@ -0,0 +1,27 @@ +import os +from io import BytesIO + +from barcode import EAN13 +from barcode.writer import ImageWriter +from barcode.writer import SVGWriter + + +PATH = os.path.dirname(os.path.abspath(__file__)) +TESTPATH = os.path.join(PATH, "test_outputs") + +if ImageWriter: + + def test_saving_image_to_byteio(): + rv = BytesIO() + EAN13(str(100000902922), writer=ImageWriter()).write(rv) + + with open(f"{TESTPATH}/somefile.jpeg", "wb") as f: + EAN13("100000011111", writer=ImageWriter()).write(f) + + +def test_saving_svg_to_byteio(): + rv = BytesIO() + EAN13(str(100000902922), writer=SVGWriter()).write(rv) + + with open(f"{TESTPATH}/somefile.svg", "wb") as f: + EAN13("100000011111", writer=SVGWriter()).write(f)