Search code examples
pythonpython-requestsshutilzpl

Creating label using ZPL Python


I am trying to create a label with QR code and with some text and save the label as PDF. I am unable to alter the size of the label to 9 X 3 cms. How do I do that?

What I tried so far?

import requests
import shutil

zpl = """
^XA
^FO50,60^A0,15^FDID 123456^FS

^FO100,100
^BQN,2,5
^FDQA,QR_CODE^FS

^FO120,270^A0,15^FDTest here^FS
^FO150,290^A0,15^FDSome more text here^FS
^FO25,25^GB500,350,2^FS

^XZ
"""

# adjust print density (8dpmm), label width (4 inches), label height (6 inches), and label index (0) as necessary
url = 'http://api.labelary.com/v1/printers/8dpmm/labels/3.5x10/0/'
files = {'file' : zpl}
headers = {'Accept' : 'application/pdf'} # omit this line to get PNG images back
response = requests.post(url, headers = headers, files = files, stream = True)

if response.status_code == 200:
    response.raw.decode_content = True
    with open('label.pdf', 'wb') as out_file: # change file name for PNG images
        shutil.copyfileobj(response.raw, out_file)
else:
    print('Error: ' + response.text)

Solution

  • You need to find the right combination of basically 4 parameters, which are:

    1. The size of your graphical elements in dots, for example the texts and the bounding box.
    2. The density (or resolution) of your label, which should match your printer's.
    3. The size of the (physical) label.
    4. The size of the PDF page.

    Here's an example of how to control each one of these.
    Only the relevant lines are shown:

    # The values in your ZPL set the sizes in dots:
    zpl = """
    ^XA
    ^FO50,60^A0,15^FDID 123456^FS
    
    ... (your full ZPL here) ...
    
    """
    
    # Then:
    
    # 1. Set the density (24dpmm) and the size of the label in inches (2.8x2):
    url = 'http://api.labelary.com/v1/printers/24dpmm/labels/2.8x2/0/'
    
    # 2. Set the PDF page size, here A4:
    headers = {'Accept' : 'application/pdf', 'X-Page-Size':'A4'}
    

    Note: if the PDF page size is not set in the header, then it will match the physical label size.