python-barcode icon indicating copy to clipboard operation
python-barcode copied to clipboard

Changing font functionality

Open jkissl opened this issue 4 years ago • 2 comments

Looking through the documentation and the code in I found the font_path argument that either defaults to a supplied font or can be passed a path to a different font. I've tried several different variations of passing a font to it and even modified writer.py directly to use a different font. Neither of those had any effect on the font that appears below the barcode. Can you provide an example of changing the font?

jkissl avatar Jan 27 '21 14:01 jkissl

I encountered this as well behavior as well. It only applies if you are writing SVGs though. If you write raster files (PNGs, JPGs, etc), the font_path option does exactly what you expect.

Looking at the SVGWriter class in class in barcode/writer.py it's pretty obvious why:

class SVGWriter(BaseWriter):
    # ...
    def _create_text(self, xpos, ypos):
        # ...
            attributes = {
                "x": SIZE.format(xpos),
                "y": SIZE.format(ypos),

                #
                # the 'font-family' attribute used by XHTML docs to render font is not set
                #
                "style": "fill:{};font-size:{}pt;text-anchor:middle;".format(
                    self.foreground,
                    self.font_size,
                ),
            }

As hacky workaround since in my use case I needed bunch of arbitrarily scalable barcodes with non-ambiguous font (a lot of fonts 0 and capitol O look identical), I just had it write the font_path option as the XHTML font-family option:

class SVGWriter(BaseWriter):
    # ...
    def _create_text(self, xpos, ypos):
        # ...
            attributes = {
                "x": SIZE.format(xpos),
                "y": SIZE.format(ypos),
                "style": "fill:{};font-size:{}pt;text-anchor:middle;font-family:'{}'".format(
                    self.foreground,
                    self.font_size,
                    self.font_path
                ),
            }

CAUTION: I am not clear on how that would interact with the SVG sizing system in the package so I didn't commit and PR this change. I wanted to take a closer look and do this more smartly if need be. Regardless, I am more than happy to work with the team on giving SVG barcodes font customizability.

ghost avatar Jan 29 '21 22:01 ghost

As suggested by ghost the trick worked well. I would like to give a tip that the font_path actually means the font name."

alexlopesbr avatar Feb 03 '24 21:02 alexlopesbr