From 017a38ce29b4e01d1b09357c94b28e84d2346967 Mon Sep 17 00:00:00 2001 From: Philipp Hagemeister Date: Fri, 19 Aug 2022 12:32:26 +0200 Subject: [PATCH] Automatically switch renderer to EPS This makes `./run -o 840147413574.eps 840147413574` generate an EPS file instead of an SVG file. --- beautiful_barcode/barcode.py | 8 +++++--- beautiful_barcode/renderers.py | 9 +++++++-- test/test_renderer.py | 13 +++++++++++++ 3 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 test/test_renderer.py diff --git a/beautiful_barcode/barcode.py b/beautiful_barcode/barcode.py index 2558d8d..4f37932 100644 --- a/beautiful_barcode/barcode.py +++ b/beautiful_barcode/barcode.py @@ -1,3 +1,5 @@ +import os.path + from . import renderers @@ -6,14 +8,14 @@ def to_modules(self) -> str: """ Convert the Barcode to modules (1 or 0) """ raise NotImplementedError - def render(self, renderer='auto') -> bytes: + def render(self, renderer='auto', extension=None) -> bytes: """ Renders the barcode as a bytes object """ - rend = renderers.make_renderer(renderer) + rend = renderers.make_renderer(renderer, extension=extension) self._paint(rend) return rend.to_bytes() def write(self, filename, renderer='auto'): - data = self.render(renderer=renderer) + data = self.render(renderer=renderer, extension=os.path.splitext(filename)[1]) with open(filename, 'wb') as out_file: out_file.write(data) diff --git a/beautiful_barcode/renderers.py b/beautiful_barcode/renderers.py index 6027f74..3788521 100644 --- a/beautiful_barcode/renderers.py +++ b/beautiful_barcode/renderers.py @@ -108,10 +108,15 @@ def text(self, characters, x, y, scale=1): x += _DIGIT_WIDTH[char] * scale -def make_renderer(spec): +def make_renderer(spec, extension=None): if isinstance(spec, SVGRenderer): return spec # Already a renderer, great - klass = NAMED_RENDERERS.get(spec, spec) + + if spec == 'auto' and extension == '.eps': + klass = InkscapeEPSRenderer + else: + klass = NAMED_RENDERERS.get(spec, spec) + return klass() diff --git a/test/test_renderer.py b/test/test_renderer.py new file mode 100644 index 0000000..f52fd6a --- /dev/null +++ b/test/test_renderer.py @@ -0,0 +1,13 @@ +import unittest + +import tutils # noqa +from beautiful_barcode.renderers import make_renderer, InkscapeEPSRenderer + + +class RendererTest(unittest.TestCase): + def test_auto_eps(self): + svg_renderer = make_renderer('auto', extension='.svg') + self.assertFalse(isinstance(svg_renderer, InkscapeEPSRenderer)) # actual result is implementation-defined + + eps_renderer = make_renderer('auto', extension='.eps') + self.assertTrue(isinstance(eps_renderer, InkscapeEPSRenderer))