Generate barcodes using reportlab

# -*-coding:utf-8 -*-
from reportlab.pdfbase import pdfmetrics
#添加中文支持
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('msyh', 'fonts/msyh.ttc'))
from reportlab.graphics import barcode
from reportlab.lib.units import cm
from reportlab.pdfgen import canvas
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.units import mm
from reportlab.graphics import renderPDF
from reportlab.lib import units
from reportlab.graphics import renderPM
from reportlab.graphics.barcode import createBarcodeDrawing

def get_barcode(value, width, barWidth = 0.05 * units.inch, fontSize = 30, humanReadable = True):

    barcode = createBarcodeDrawing('Code128', value = value, barWidth = barWidth, fontSize = fontSize, humanReadable = humanReadable)

    drawing_width = width
    barcode_scale = drawing_width / barcode.width
    drawing_height = barcode.height * barcode_scale

    drawing = Drawing(drawing_width, drawing_height)
    drawing.scale(barcode_scale, barcode_scale)
    drawing.add(barcode, name='barcode')

    return drawing

def get_image():

    barcode = get_barcode(value = '01234567890', width = 300)
    renderPM.drawToString(barcode, fmt = 'PNG')
    f = 'temp/test.png'
    renderPM.drawToFile(barcode,fn=f,fmt='png')
    
get_image()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065744&siteId=291194637
Recommended