Skip to content

Instantly share code, notes, and snippets.

@ctheune
Last active October 15, 2022 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctheune/329cf91b3cd272be4ce480a206dc5de4 to your computer and use it in GitHub Desktop.
Save ctheune/329cf91b3cd272be4ce480a206dc5de4 to your computer and use it in GitHub Desktop.
Parse Snipe IT label HTML and create nice PDF for Zebra ZD420
from reportlab.graphics.barcode import code39, code128, code93
from reportlab.graphics.barcode import eanbc, qr, usps
from reportlab.graphics.shapes import Drawing
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, Frame
from reportlab.lib.styles import getSampleStyleSheet
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleN.fontSize = 6
styleN.fontName = 'Meta'
styleN.allowOrphans = 1
styleN.leading = 6
styleN.borderPadding = 0
styleN.leftIndent = 0
import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('Meta', 'MetaOT-Medi.ttf'))
pdfmetrics.registerFont(TTFont('SourceCodePro', 'SourceCodePro-Medium.ttf'))
import lxml.html
tree = lxml.html.fromstring(open('/Users/ctheune/Labels.html').read())
#----------------------------------------------------------------------
def createBarCodes():
"""
Create barcode examples and embed in a PDF
"""
c = canvas.Canvas("label.pdf", pagesize=(2*inch, 1*inch))
for label in tree.find_class('label'):
label_data = {}
for line in label.text_content().splitlines():
line = line.strip()
if not line:
continue
if ':' in line:
key, value = line.split(':', maxsplit=1)
label_data[key] = value.strip()
if label_data['C'] == 'Flying Circus':
label_data['C'] = 'Flying Circus Internet Operations GmbH'
label_data['ID'] = int(label_data['T'].replace('FC', ''))
print(label_data)
# Company
c.setFont("Meta", 5)
c.drawString(0.6*inch, 0.08*inch, label_data['C'])
# Tag
c.setFont("SourceCodePro", 19)
c.drawString(0.6*inch, 0.2*inch, label_data['T'])
# Model
model = [Paragraph(label_data['M'], style=styleN)]
f = Frame(0, 0.6*inch, 2*inch, 0.45*inch, showBoundary=0)
f.addFromList(model, c)
# draw a QR code
qr_code = qr.QrCodeWidget(f'https://assets.flyingcircus.io/hardware/{label_data["ID"]}')
bounds = qr_code.getBounds()
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
d = Drawing(45, 45, transform=[45./width,0,0,45./height,0,0])
d.add(qr_code)
renderPDF.draw(d, c, 0, 0)
c.showPage()
c.save()
if __name__ == "__main__":
createBarCodes()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment