Skip to content

Commit

Permalink
Automatically switch renderer to EPS
Browse files Browse the repository at this point in the history
This makes `./run -o 840147413574.eps 840147413574` generate an EPS file instead of an SVG file.
  • Loading branch information
phihag committed Aug 19, 2022
1 parent 14c682a commit 017a38c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
8 changes: 5 additions & 3 deletions beautiful_barcode/barcode.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os.path

from . import renderers


Expand All @@ -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)
9 changes: 7 additions & 2 deletions beautiful_barcode/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()


Expand Down
13 changes: 13 additions & 0 deletions test/test_renderer.py
Original file line number Diff line number Diff line change
@@ -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))

0 comments on commit 017a38c

Please sign in to comment.