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

how to set height and width if writing to file like object?

Open israelcoper opened this issue 5 years ago • 3 comments

Here's my code:

def barcode_to_html(order_id, box_num):

    from barcode import Code128
    from barcode.writer import ImageWriter
    from io import BytesIO
    import base64

    file_like_object = BytesIO()

    writer = ImageWriter()
    writer.set_options({ 'module_height': 10.0 })  ## NOT WORKING

    value = f'{order_id}-{box_num}'

    Code128(value, writer=writer).write(file_like_object)

    encoded = base64.b64encode(file_like_object.getvalue()).decode("ascii")

    return f'<img src="data:image/png;base64,{encoded}"  />'

israelcoper avatar Oct 01 '20 10:10 israelcoper

I had this issue aswell, its not totally clear in the documentation but you can pass the options to .write() instead:

Code128(value, writer=writer).write(file_like_object, options={'<option>': <value>})

jhummer avatar Dec 04 '20 07:12 jhummer

Use the options this way ,

     from barcode import ITF
     from io import BytesIO
     stream = BytesIO()
     options = {
             "module_width": 0.1,
             "module_height": 2,
             "quiet_zone": 0.1,
             "write_text": False,
             "text_distance": 2,
     }
     Code128(code_str, writer=writer1, narrow=1, wide=3).write(stream, options)

avmakesh avatar Feb 02 '22 10:02 avmakesh

I did it this way, hoping it can help you.

from barcode.writer import ImageWriter
from barcode import Code128

code128 = Code128(code, writer=ImageWriter())
code128.save(filename=f"{code}", options={"module_width": 0.5})

Etuloser avatar Jan 18 '24 03:01 Etuloser