adamchainz / treepoem

Barcode rendering for Python supporting QRcode, Aztec, PDF417, I25, Code128, Code39 and many more types.
MIT License
129 stars 26 forks source link

How to add barcode margins? #286

Closed hazardland closed 3 years ago

hazardland commented 3 years ago

Any ideas how to add barcode margins?

I generate PDF and EPS using treepoem, the white space is a PDF page, local polygraph companies require to have margins around barcodes, is it possible somehow?

image

image

image

image

adamchainz commented 3 years ago

Post process the image with eg Pillow.

hazardland commented 3 years ago

@adamchainz kk I fixed it by modifying bbox_lines in generate_barcode, now itf14 box has left border also:

image

Original code produces (See it has no left border): image

In case someone will need it in future:

# -*- encoding:utf-8 -*-
import io
import subprocess
from treepoem.__init__ import _format_code, _get_bbox, EPS_TEMPLATE, BWIPP, _get_ghostscript_binary, EpsImagePlugin
from treepoem.data import barcode_types

def bbox_add(source, number):
    if number is None:
        return source
    return str(float(source) + number)

def bbox_expand(bbox_lines, left=None, bottom=None, right=None, top=None):
    bbox = bbox_lines.split("\n")
    bbox_0 = bbox[0].split(' ')
    bbox_1 = bbox[1].split(' ')
    return f"""{bbox_0[0]} {bbox_add(bbox_0[1], left)} {bbox_add(bbox_0[2], bottom)} {bbox_add(bbox_0[3], right)} {bbox_add(bbox_0[4], top)}
{bbox_1[0]} {bbox_add(bbox_1[1], left)} {bbox_add(bbox_1[2], bottom)} {bbox_add(bbox_1[3], right)} {bbox_add(bbox_1[4], top)}"""

def generate_barcode(barcode_type, data, options=None):
    if barcode_type not in barcode_types:
        raise NotImplementedError('unsupported barcode type {!r}'.format(barcode_type))
    if options is None:
        options = {}
    code = _format_code(barcode_type, data, options)
    bbox_lines = _get_bbox(code)

    # Fix bbox lines
    if barcode_type == 'itf14':
        bbox_lines = bbox_expand(bbox_lines, left=-20, bottom=-5, right=5, top=5)
    else:
        bbox_lines = bbox_expand(bbox_lines, left=-5, bottom=-5, right=5, top=5)

    full_code = EPS_TEMPLATE.format(bbox=bbox_lines, bwipp=BWIPP, code=code)
    return EpsImagePlugin.EpsImageFile(io.BytesIO(full_code.encode("utf8")))