Coder Social home page Coder Social logo

adamchainz / treepoem Goto Github PK

View Code? Open in Web Editor NEW
124.0 11.0 23.0 1.82 MB

Barcode rendering for Python supporting QRcode, Aztec, PDF417, I25, Code128, Code39 and many more types.

License: MIT License

Python 3.54% PostScript 96.46%
python barcod bwipp

treepoem's Introduction

Treepoem

https://img.shields.io/github/actions/workflow/status/adamchainz/treepoem/main.yml?branch=main&style=for-the-badge https://img.shields.io/pypi/v/treepoem.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

A cleverly named, but very simple python barcode renderer wrapping the BWIPP library and ghostscript command line tool.


Improve your Django and Git skills with one of my books.


Installation

Install from pip:

python -m pip install treepoem

Python 3.8 to 3.12 supported.

You'll also need Ghostscript installed. On Ubuntu/Debian this can be installed with:

apt-get install ghostscript

On Mac OS X use:

brew install ghostscript

Otherwise refer to your distribution's package manager, though it's likely to be called ghostscript too.

There's a known issue with rendering on Ghostscript 9.22+ where images are smeared. See GitHub Issue #124 and its associated links for more details. Ghostscript merged a fix in version 9.26 and common barcodes seem to work from then on, though still with some smearing.

You can check your Ghostscript version with:

gs --version

API

generate_barcode(barcode_type: str, data: str | bytes, options: dict[str, str | bool] | None=None, *, scale: int = 2) -> Image

Generates a barcode and returns it as a PIL Image object

barcode_type is the name of the barcode type to generate (see below).

data is a str or bytes of data to embed in the barcode - the amount that can be embedded varies by type.

options is a dictionary of strings-to-strings of extra options to be passed to BWIPP, as per its docs.

scale controls the output image size. Use 1 for the smallest image and larger values for larger images.

For example, this generates a QR code image, and saves it to a file using Image.save():

import treepoem

image = treepoem.generate_barcode(
    barcode_type="qrcode",  # One of the BWIPP supported codes.
    data="barcode payload",
)
image.convert("1").save("barcode.png")

If your barcode image is monochrome, with no additional text or colouring, converting the Image object to monochrome (image.convert("1")) will likely reduce its file size.

barcode_types: dict[str, BarcodeType]

This is a dict of the ~100 names of the barcode types that the vendored version of BWIPP supports: its keys are strs of the barcode type encoder names, and the values are instances of BarcodeType.

BarcodeType

A class representing meta information on the types. It has two attributes:

  • type_code - the value needed for the barcode_type argument of generate_barcode() to use this type.
  • description - the human level description of the type which has two str.

Only these common types are used in the test suite:

Command-line interface

Treepoem also includes a simple command-line interface to the functionality of generate_barcode. For example, these commands will generate two QR codes with identical contents, but different levels of error correction (see QR Code Options):

$ treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H
$ treepoem -o barcode2.png -t qrcode "^084his is a test" eclevel=L parse

Complete usage instructions are shown with treepoem --help.

What's so clever about the name?

Barcode.

Bark ode.

Tree poem.

Updating BWIPP

For development of treepoem, when there's a new BWIPP release:

  1. Run ./download_bwipp.py with the version of BWIPP to download.
  2. Run ./make_data.py to update the barcode types that treepoem knows about.
  3. Add a note in CHANGELOG.rst about the upgrade, adapting from the previous one.
  4. Commit and make a pull request, adapting from previous examples.

treepoem's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

treepoem's Issues

Text under barcode is pixelated and although readable its not very clear

Python Version

3.11.1

Package Version

treepoem 3.18.0

Description

Is there any way to make the text clearer (more crisp) once rendered? Included a saved PNG as example.

image = treepoem.generate_barcode(barcode_type="sscc18", data=sscc_preliminary, options={'includetext': True, 'textfont': 'Times-Roman'})
data = io.BytesIO()
image.convert("1").save(data,"PNG")
image.save("barcode.png")

barcode

test failures on PowerPC ppc64le

I am trying to build treepoem on rhel 7.6 ppc64le. The build passes, however there are 3 test failures:

ERRORS:
FAILED tests/test_treepoem.py::test_barcode[interleaved2of5-0123456789] - assert (2, 1, 195, 145) is None
FAILED tests/test_treepoem.py::test_barcode[code128-This is code128 barcode.] - assert (4, 1, 593, 145) is None
FAILED tests/test_treepoem.py::test_barcode[code39-THIS IS CODE39 BARCODE.] - assert (2, 1, 795, 145) is None

Python version: Python 3.6.3
Environment : Rhel 7.6 ppc64le
Pip: pip 20.0.2 from /opt/rh/rh-python36/root/usr/lib/python3.6/site-packages/pip (python 3.6)
Ghostscript 9.07

Would like some help on this issue. I am running it on a High end VM with good connectivity.

Byte string data

Description

Hi everyone!

Is it possible to get the byte string data object for datamatrix?

Documentation needed for specifying "parse" or "raw" in azteccode

Newer to python, but I cannot pass either "raw" or "parse" .

passing:
options={"format":"full", "layers":"4"} works just fine for specifying a full full Aztec code with 4 layers, but how do you pass the option for parse or raw?

Need documentation on how to accomplish something like below:
options={"parse":"true"}

Is this really easy and I am missing something?

OSError: [Errno 2] No such file or directory on Mac ElCapitan

Hi, got this when trying to call generate_barcode...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/treepoem/__init__.py", line 123, in generate_barcode
    bbox_lines = _get_bbox(code)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/treepoem/__init__.py", line 84, in _get_bbox
    stderr=subprocess.PIPE,
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Ghostscript error

Previously this has been skirted as a non treepoem issue, but I think this is definitely has to do treepoem not able to obtain correct bounding box while using inherent template. I think other people have also faced the problem, but closing the issue is not solving this problem. Let's keep this open and try to figure out the exact mechanism of what is going on.

$ treepoem -o barcode1.png -t gs1datamatrix   "TEST" format=square version=20x20
Traceback (most recent call last):
  File "/home/s/v/bin/treepoem", line 11, in <module>
    sys.exit(main())
  File "/home/s/v/lib/python3.6/site-packages/treepoem/__main__.py", line 62, in main
    image = generate_barcode(args.type, args.data, dict(args.options))
  File "/home/s/v/lib/python3.6/site-packages/treepoem/__init__.py", line 149, in generate_barcode
    bbox_lines = _get_bbox(code)
  File "/home/s/v/lib/python3.6/site-packages/treepoem/__init__.py", line 101, in _get_bbox
    raise TreepoemError(err_output)
treepoem.TreepoemError: GPL Ghostscript 9.26: Unrecoverable error, exit code 1

GS1-128 Barcode Generation

I am trying to generate a GS1-128 barcode but I am running into this exception.
import treepoem

image = treepoem.generate_barcode(
barcode_type='gs1-128', # One of the BWIPP supported codes.
data=b'0101234567890128TEC-IT',
)
image.convert('1').save('barcodsawefe.png')

Traceback (most recent call last):
File "D:/Fiverr/PdfCoupons/test.py", line 14, in
data=b'0101234567890128TEC-IT',
File "D:\Fiverr\PdfCoupons\venv\lib\site-packages\treepoem_init_.py", line 142, in generate_barcode
bbox_lines = get_bbox(code)
File "D:\Fiverr\PdfCoupons\venv\lib\site-packages\treepoem_init
.py", line 94, in _get_bbox
raise TreepoemError(err_output)
treepoem.TreepoemError: GPL Ghostscript 9.27: Unrecoverable error, exit code 1

Insert FCN1 character into Code128 string

Is there a way to insert an FCN1 character into an arbitrary place in a code128 data string prior to encoding?

This code produces the barcode that I want, except that I need an FCN1 character between 42007086 and 92...

tn = '4200708692612903017213001000000091'

image = treepoem.generate_barcode(
barcode_type='code128',
data=tn,
)

Test fixtures generate differently on newer versions of ghostscript

Currently on Travis ghostscript 9.10 is used, and it's compatible with the files in tests/fixtures/. However on my Mac I now get version 9.23 and that leads to the tests failing. It seems that one extra pixel is (wrongly?) drawn on newer versions. Perhaps there's some argument we can pass to newer ghostscript versions to preserve the apparently correct older rendering.

includetext doesn't work on sscc generation

for the options field, we must pass a dictionary

image = treepoem.generate_barcode(barcode_type='sscc18',data="(00)00614141123456789",options={"height":"1"})

this works, however, I can't put options={"includetext"}, since it needs either an element and True, or "" don't seem to be working.

any clue?

How to get nice EAN13 and EAN14?

I see nice examples, but each time i try to generate EAN13 or EAN14 i get something very strange. I tried to get bigger resolution and font, but no luck to get simething nice i see everywhere. Please, can you send me options you use to generate EANs?

ean13_barcode = treepoem.generate_barcode(barcode_type='ean13', data=ean13_gen, options={'guardwhitespace': True, 'includetext': True, 'textsize': '19', 'height': '3', 'width': '5'})

generates:
https://ibb.co/3C2Y513

ean13_barcode = treepoem.generate_barcode(barcode_type='ean13', data=ean13_gen, options={'includetext': True, 'height': '3', 'width': '5'})

generates:
https://ibb.co/y8yt8Z4

ean14_barcode = treepoem.generate_barcode(barcode_type='ean14', data=ean14_gen, options={'includetext': True, 'textsize': '13', 'height': '3', 'width': '5'})

generates:
https://ibb.co/S7zC822

Any tips what to put to options to get better image? If i try bigger font, it's out of canvas, instead of writing into bars.

code93 barcodes are apparently invalid

excellent library name, thank you.

I've been trying to generate bar codes with both code93 and code93ext. Unfortunately the barcodes generate seem to be invalid - when i try scanning them with an app on my phone and a barcode scanning site they're not recognised (when I try reading the code93 bar code from the wikipedia article it's read immediately).

My code:

from treepoem import generate_barcode
image = generate_barcode('code93', b'1234 5678')
image.convert('1').save('code93.png')

am I doing something wrong, or is there a problem with generating these barcodes?

Ghostscript crashes when using round brackets in 'alttext' option value

Reproduce - Treepoem 3.3.8 - Ghostscript 9.52

from treepoem import _get_bbox, _format_code

_get_bbox(_format_code('code128', '(01)04860119720024(11)210117', {'alttext':'(01)04860119720024(11)210117'}))

# data = '(01)04860119720024(11)210117'
# data = ']C1'+data.replace('(', '').replace(')', '')

Output:

Traceback (most recent call last):                                                                                                                                         
  File "gen_barcode.py", line 3, in <module>                                                                                                                               
    _get_bbox(_format_code('code128', '(01)04860119720024(11)210117', {'alttext':'(01)04860119720024(11)210117'}))                                                         
  File "C:\Users\BIOHAZARD\AppData\Local\Programs\Python\Python36\lib\site-packages\treepoem\__init__.py", line 100, in _get_bbox                                          
    raise TreepoemError(err_output)                                                                                                                                        
treepoem.TreepoemError: GPL Ghostscript 9.52: Unrecoverable error, exit code 1  

In case of code128 barcode data text needs to be different and must be formatted like this:

data = '(01)04860119720024(11)210117'
_get_bbox(_format_code('code128', ']C1'+data.replace('(', '').replace(')', ''), {'alttext':data}))

All generated barcodes have dark backgrounds

Python Version

No response

Package Version

No response

Description

All barcodes that I generate with Treepoem have been generating more as dark gray and black rather than white and black. This is even using the image.convert('1') conversion. This does brighten them up very slightly but they are still extremely dark. This happens for me with any type of barcode.

Create PD417 fails

Python Version

3.7.3

Package Version

3.14.0

Description

I am trying to create PDF417 with the data below.

I have installed the treepoem package from PyPi and tried
image = treepoem.generate_barcode( barcode_type="pdf417",data=text)
image.convert("1").save("barc.png")

UPDATE I have found that I can have up to 794 characters in the barcode before this error occurs
But there I get
Error GPL Ghostscript 9.27:Unrecoverable error , exit code 1

text="AZsJRZJwvaYTfBl309+UaA7JyhiSQeb36e50lo0rvxRG6K70iJ8dLtxBPJT2VQqnVSVVSQPud+gCArWp+GA2esgcnnFxQSEvXwqLEw5WDHX2hCscJxhK9lKKhNGBCVE4NDpkTGcZOoriKAX1wYOdQqWDmxnPeYLvD8W8BldrLvaRneKCIaUJj8+z4HET4qBSXRA4EA/Qr1iXpFN0pLwgYu8/gAPSoeRSZNxg9LH4cFBqgQfmOjOB+SnD0Q5Ji8PFv/z2T93c6QKgKS94Whk9LfqJ1PNJFWRFvwkLHGSvESq39uc506hAPh6E3QVJfcWMTWnRBCVfhsjwn+MX03jjcZKlF+q1GEiye0zyI+Lz8r0K3BMVLwM9TaZWDzN8OAKcD5Dh2iUu8tiX/nsKowIeWMCSvUAbRKnXHxDbIGV65IGVTUqsgnM4/VsyPnjfCZ1FmxVIhlzRJVwJPvJIn7ZD0aL+SAGb8lWy76Zj2VclXvBmBjXxA4V17401K8PHbR/j3gTrfoGiCYjEzZzop82ZTdqCSV1AeHVHFvdJvhDrFN3X+ItFAZG+draXyrr76+6CVyNNtlpA8s5gO6sY5n1ngljAGtkPl3TlpG1xqqCYK1JS+N5sCKUMuOGzskjW2hA1/5pg7ZSm1GepM+OMbm44/mLMNih838QJYU+GcihcIGrK/Zq+B96vWVluqyFuY4+PU8XnseaHvOAbUJ7jk2lc71GGD/kyMoIZpBSA3HUTkJ9HW6uKgncbaQeNl6q0lMQMCRfjF4BO1vFOnp5FQWrYmsYrJdLrlQXC+89aXUEWWFb2UBDEH2ZlYECp8FbiPSEQGPLyNRYVy228TN5Rn7vZpWVwPer3TcoMNF7TWHycXcU2mmQypsqdf/jgw/Isd7Vc3gK0BBIKdMMrYzkpu88V7PbDBO6mHHNKORxfG1fVQ2jW7JoXk+ZYhEL4/I4="

EAN13 bbox out of bounds after bwipp change

Python Version

3.9.6

Package Version

3.22.0

Description

Hi @adamchainz ,

after this bwipp commit bwipp/postscriptbarcode@b4ae9e1 and the changes made to the ean13.ps line 59 the first diget is plotted out of bounds.

Here is an example (see the 4 at the very beginning):

4260661767605_8204

Before the change:

4260661767605_8204

So we can see that the initial character was shifted left, however it now results in a position negative to the coordinate roots.

A very crude hack to solve the problem temporarily for EAN13 is to fix bbox boundaries manually in def _get_bbox resulting in:

4260661767605_8204

Note, that due to the bwipp change the distance between the initial number and the first bar increased slightly.

Just for your interest, the temp hack for ean13 only:

    bounding_box_pattern = r"(%%BoundingBox:) ([0-9]+) ([0-9]+ [0-9]+ [0-9]+.*)"
    bounding_box_replacement = r"\1 " + f"-{scale} " + r"\3"
    err_output = re.sub(
        bounding_box_pattern, 
        bounding_box_replacement, 
        err_output, 
        count=1
    )

    bounding_box_pattern = r"(%%HiResBoundingBox:) ([0-9]+.[0-9]{6}) ([0-9]+.[0-9]{6} [0-9]+.[0-9]{6} [0-9]+.[0-9]{6})"
    bounding_box_replacement =  r"\1 " + f"-{scale:.6f} " + r"\3"
    err_output = re.sub(
        bounding_box_pattern, 
        bounding_box_replacement, 
        err_output, 
        count=1
    )

I am not sure if this requires just an additional ghostscript flag or a fix to bwipp. Please let me know your thoughts.

(I have ghostscript version 10.01.2 installed.)

Best
Nico

Barcode type 'UPC-A' missing check digit.

When using UPC-A barcode type, it fails to generate the check digit.
I have tried the options, 'includecheck' and 'includecheckintext', and it generates the barcode missing the check digit.
Example code:
image = tp.generate_barcode(barcode_type='upca', data='73829444752', options={'includetext textsize=5': True,'includecheck': True,'includecheckintext': True, 'addontextxoffset': 10})

When using with barcode_type = 'royalmail', it correctly generates the check digit.

Please help and thank you in advance.

Licensing question

Python Version

No response

Package Version

No response

Description

Hello everyone. I have a question for the library. Since treepoem is under MIT, but GhostScript is behind AGPL, does that mean I have to follow the AGPL license?

ITF-14 broken

Left border of the ITF-14 bounding box border is not being rendered. See image below
barcode

run treepoem in a docker

I can generate Barcode in a virtualenv with this lib,but there is an error in a docker.
Why?

File "/usr/local/lib/python3.5/site-packages/treepoem/init.py", line 140, in generate_barcode
bbox_lines = _get_bbox(code)
File "/usr/local/lib/python3.5/site-packages/treepoem/init.py", line 83, in _get_bbox
stderr=subprocess.PIPE,
File "/usr/local/lib/python3.5/subprocess.py", line 676, in init
restore_signals, start_new_session)
File "/usr/local/lib/python3.5/subprocess.py", line 1289, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'gs'

Fix `IOError`

  File "/path/to/venv/local/lib/python2.7/site-packages/treepoem/__init__.py", line 74, in <module>
    BWIPP = _read_file(BWIPP_PATH)
  File "/path/to/venv/local/lib/python2.7/site-packages/treepoem/__init__.py", line 71, in _read_file
    with open(file_path) as f:
IOError: [Errno 2] No such file or directory: u'/path/to/venv/local/lib/python2.7/site-packages/treepoem/postscriptbarcode/barcode.ps'

The BWIPP files aren't packaged! 😵

Fix `ResourceWarnings`

As seen in any recent Travis CI build python3 test runs have this output:

test_barcode (tests.test_treepoem.TreepoemTestCase) ... /Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
/Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
/Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
/Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
/Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
/Users/julius/work/code/treepoem/.tox/py35/lib/python3.5/site-packages/PIL/EpsImagePlugin.py:337: ResourceWarning: unclosed file <_io.BufferedReader name=9>
  self.im = Ghostscript(self.tile, self.size, self.fp, scale)
ok

This is most likely Pillow library issue. I traced it back to EpsImageFile.load & EpsImagePlugins.Ghostscript constructor and something to do with handling of temporary files.

Can we generate in bmp image format

Hi, Is there a way� that the image can be generated in BMP format? I am trying to generate Aztec code in BMP format.
Sorry to post this question as an issue.

How to add barcode margins?

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

Azteccode generate fails with version 3.5.0 and specific payload

With the following test code running with Treepoem version 3.5.0 we get a error : "GPL Ghostscript 9.27: Unrecoverable error, exit code 1"
also tried it with Ghostscript 9.53.3, same issue, downgrading to Treepoem 3.4.0 solved the problem.

With this specific data it will always fail, other data (like bytes(range(25)) ) generates an image, without a problem

treepoem.generate_barcode( barcode_type="azteccode", data=bytes(range(256)), options={"layers": 17, "format": "full"}, )

Does not support binary data (workaround included)

I am creating Aztec barcodes that contain binary data. I found I needed to perform a trick to decode my data into a string because treepoem will encode it:

data=data.decode("ascii", errors="ignore")

Maybe treepoem could check if the data is already in bytes.

(Otherwise, great little package. Works out of the box!)

Incompatibility with GS10

Python Version

Python 3.11.0

Package Version

3.17.0

Description

Gretings

with gs 10 : I get the following error, when I installed 9.5.4 no issues.

treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H

The GS window pops up and if I then close it I get the following message

PS C:\Users\User> treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H
treepoem : Traceback (most recent call last):
At line:1 char:1

  • treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H
  •   + CategoryInfo          : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError
    
    File "<frozen runpy>", line 198, in _run_module_as_main
    File "<frozen runpy>", line 88, in _run_code
    File "C:\Python\Scripts\treepoem.exe\__main__.py", line 7, in <module>
    File "C:\Python\Lib\site-packages\treepoem\__main__.py", line 66, in main
      image = generate_barcode(type_, data, options)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Python\Lib\site-packages\treepoem\__init__.py", line 158, in generate_barcode
      bbox_lines = _get_bbox(code)
                   ^^^^^^^^^^^^^^^
    File "C:\Python\Lib\site-packages\treepoem\__init__.py", line 102, in _get_bbox
      raise TreepoemError(err_output)
    

treepoem.TreepoemError

Add support custom fonts (for string below barcode)

How could use font family Bolonewt? I tried all of Times-Roman, Times-Italic, Times-Bold, Times-BoldItalic, Helvetica, Helvetica-Oblique, Helvetica-Bold, Helvetica-BoldOblique, Courier, Courier-Oblique, Courier-Bold, Courier-BoldOblique or Symbol. But it turns out that this is not something that we need. we have figured out that we need Bolonewt font family. But I am not able to find a way to use this new font family. Please help.

Ghostscript v9.26 build fails on PowerPC ppc64le

W.R.T #215 I was trying to build Ghostscript 9.26 on rhel 7.6 ppc64le, However the build fails with the following error:

./sobin/libgs.so: undefined reference to ``png_init_filter_functions_vsx'`
`collect2: error: ld returned 1 exit status

yum install ghostscript installs ghostscript v9.07 due to which treepoem produces test failures.
Would like some help on this.

Generating multiple barcodes without reopening the gs subprocess?

I'm trying to figure out whether there's a reasonable way to generate multiple barcode images without reopening the gs subprocess and reinterpreting the BWIPP source — which are rather "heavyweight" and slow operations.

It seems like this should be eminently possible. See below: ./multi_barcode.py (run as multi_barcode.py "bc1" "bc2" ....

Problems I'm having:

  1. I can't figure out how to make this work with EPS, because the eps2write driver doesn't like switching output files.
  2. I can't figure out how to measure the bounding box and output the correct-sized image in a single pass.
#!/usr/bin/python3

from treepoem import BWIPP
from binascii import hexlify
import os, sys, subprocess, time

ghostscript = 'gs'
barcode_ps = '/home/dlenski/build/treepoem/treepoem/postscriptbarcode/barcode.ps'

gs_process = subprocess.Popen(
    [ghostscript,  '-dNOPAUSE', '-sDEVICE=pngmono', '-q'],
    universal_newlines=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)
gs_process.stdin.write('<{}> run\n'.format(hexlify(barcode_ps.encode()).decode()))

for ii, code in enumerate(sys.argv[1:]):
    ofn = '/tmp/test-%d.png' % ii
    options = 'includetext'
    symbology = 'code128'

    print("Generating barcode for %s to file %s" % (code, ofn))
    try: os.unlink(ofn)
    except: pass
    
    fields = {k:hexlify(v.encode()).decode() for k,v in {'ofn':ofn, 'code':code, 'options':options, 'symbology':symbology}.items()}
    gs_process.stdin.write('''
        << /OutputFile <{ofn}> >> setpagedevice
        /Helvetica findfont 10 scalefont setfont
        gsave
        2 2 scale
        10 10 moveto

        <{code}> <{options}> <{symbology}> cvn
        /uk.co.terryburton.bwipp findresource exec
        grestore

        showpage
        '''.format(**fields))
    try:
        gs_process.stdin.flush()
    except:
        print(gs_process.communicate())

    st = None
    for ii in range(4):
        try:
            st = os.stat(ofn)
        except FileNotFoundError:
            time.sleep(1)
        else:
            break
    if not st:
        print("ERROR: File %s not created after %d seconds." % (ofn, ii))
    else:
        print("OKAY: File %s (%dB) created after %d seconds." % (ofn, st.st_size, ii))
    
else:
    stdout, stderr = gs_process.communicate()
    print("STDOUT: %s" % stdout)
    print("STDERR: %s" % stderr)

adding image title

do you know how to add barcode title while generating a barcode? I have checked on the internet, haven't seen anything about this? Could you please help me.

[WIN10] TreepoemError: Cannot determine path to ghostscript, is it installed?

Hello,

My operating system is Windows 10. The last ghostscript version is installed. Also, the "bin" and "lib" ghostscript directores are added to the windows path. However, using the following example, Treepoem can not locate ghostscript. How the problem can be solved?

Thanks & regards,
Andrés

import treepoem
image = treepoem.generate_barcode(
     barcode_type='qrcode',  # One of the BWIPP supported codes.
     data='barcode payload',
     options={},
)
image.save('barcode.png')  # This is an instance of `PIL.EpsImagePlugin.EpsImageFile`
TreepoemError                             Traceback (most recent call last)
<ipython-input-9-5e7339c46fdf> in <module>()
      6      barcode_type='qrcode',  # One of the BWIPP supported codes.
      7      data='barcode payload',
----> 8      options={},
      9 )
     10 image.save('barcode.png')  # This is an instance of `PIL.EpsImagePlugin.EpsImageFile`

C:\Anaconda3\lib\site-packages\treepoem\__init__.py in generate_barcode(barcode_type, data, options)
    135 def generate_barcode(barcode_type, data, options):
    136     code = _format_code(barcode_type, data, options)
--> 137     bbox_lines = _get_bbox(code)
    138     full_code = EPS_TEMPLATE.format(bbox=bbox_lines, bwipp=BWIPP, code=code)
    139     return EpsImagePlugin.EpsImageFile(io.BytesIO(full_code.encode('utf8')))

C:\Anaconda3\lib\site-packages\treepoem\__init__.py in _get_bbox(code)
     77 def _get_bbox(code):
     78     full_code = BBOX_TEMPLATE.format(bwipp=BWIPP, code=code)
---> 79     ghostscript = _get_ghostscript_binary()
     80     gs_process = subprocess.Popen(
     81         [ghostscript,  '-sDEVICE=bbox', '-dBATCH', '-dSAFER', '-'],

C:\Anaconda3\lib\site-packages\treepoem\__init__.py in _get_ghostscript_binary()
    104         if not binary:
    105             raise TreepoemError(
--> 106                 'Cannot determine path to ghostscript, is it installed?'
    107             )
    108 

TreepoemError: Cannot determine path to ghostscript, is it installed?

Not able to find barcode.ps'

I am trying to create barcode generator with treepoem lib and it is generating also its working perfectly with python script I am using. But, when I create exe from script and try to run that script it gives following error:

Traceback (most recent call last):
File "Barcode.py", line 1, in
File "", line 983, in _find_and_load
File "", line 967, in find_and_load_unlocked
File "", line 677, in load_unlocked
File "c:\program files (x86)\microsoft visual studio\shared\python37_64\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
exec(bytecode, module.dict)
File "treepoem_init
.py", line 79, in
File "treepoem_init
.py", line 75, in _read_file
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\HEMANT~1\AppData\Local\Temp\_MEI136082\treepoem\postscriptbarcode\barcode.ps'
[3744] Failed to execute script Barcode

It is looking for barcode.ps which it is not able to find and program return error:

The script file I am using contains following code


import treepoem
import pyodbc
import ctypes
import os
import sys

Btype=sys.argv[1]

conn_str = (
r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};"
r"DBQ=C:\Users\Hemant Shrimali\source\repos\Barcode Generator\Barcode Generator\bin\Debug\database.mdb;"
)
cnxn = pyodbc.connect(conn_str)
crsr = cnxn.cursor()
crsr.execute("select SNO,Barcode from Barcode")

from ctypes.wintypes import MAX_PATH
dll = ctypes.windll.shell32
buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
path=buf.value
directory = "Barcode"
path = os.path.join(path, directory)
os.chdir(path)
else:
print("Failure!")

for row in crsr.fetchall():
image = treepoem.generate_barcode(barcode_type=Btype,data=row.Barcode,)
image.convert("1").save(str(row.SNO)+".png")

crsr.close()
cnxn.close()


how to set font

default is /textfont (Courier) def
how to set to "DejaVu Sans Mono"

Unexpected aztec code size limitation

Python Version

3.10.0

Package Version

3.18.0

Description

Aztec codes seem to have a hard capacity limitation of 1248 bytes. Online resources suggest the maximum capacity to encode bytes is at 1914 bytes (e. g., Wikipedia). The capacity of 1914 bytes also includes the error correction words. Using the default error correction settings, we should end up with a capacity constraint of around 1550 bytes (1914 / 1.23). Encoding 1248 bytes should thus be possible.

The following fails with treepoem.TreepoemError: GPL Ghostscript 9.55.0: Unrecoverable error, exit code 1

import treepoem
treepoem.generate_barcode('azteccode', bytes.fromhex('00' * 1248))

However, using one less byte, I can still dial up the eclevel to 49% before the capacity is exhausted:

import treepoem
treepoem.generate_barcode('azteccode', bytes.fromhex('00' * 1247), {'eclevel': 49})

So the limitation above seems to make no sense. Or am I missing something?

Drop Python 2 Support

Drop Python 2 support like I have done for most of the other repositories I maintain.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.