Python之ReportLab绘制条形码和二维码的实例

yipeiwu_com5年前Python基础

条形码和二维码

#引入所需要的基本包
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
#----------------------------------------------------------------------
def createBarCodes(c):
  barcode_value = "1234567890"
  barcode39 = code39.Extended39(barcode_value)
  barcode39Std = code39.Standard39(barcode_value, barHeight=20, stop=1)
  # code93 also has an Extended and MultiWidth version
  barcode93 = code93.Standard93(barcode_value)
  barcode128 = code128.Code128(barcode_value)
  # the multiwidth barcode appears to be broken 
  #barcode128Multi = code128.MultiWidthBarcode(barcode_value)
  barcode_usps = usps.POSTNET("50158-9999")
  codes = [barcode39, barcode39Std, barcode93, barcode128, barcode_usps]
  x = 1 * mm
  y = 285 * mm
  for code in codes:
    code.drawOn(c, x, y)
    y = y - 15 * mm
  # draw the eanbc8 code
  barcode_eanbc8 = eanbc.Ean8BarcodeWidget(barcode_value)
  d = Drawing(50, 10)
  d.add(barcode_eanbc8)
  renderPDF.draw(d, c, 15, 555)
  # draw the eanbc13 code
  barcode_eanbc13 = eanbc.Ean13BarcodeWidget(barcode_value)
  d = Drawing(50, 10)
  d.add(barcode_eanbc13)
  renderPDF.draw(d, c, 15, 465)
  # draw a QR code
  qr_code = qr.QrCodeWidget('http://blog.csdn.net/webzhuce')
  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, 15, 405)
#定义要生成的pdf的名称
c=canvas.Canvas("barcodes.pdf")
#调用函数生成条形码和二维码,并将canvas对象作为参数传递
createBarCodes(c)
#showPage函数:保存当前页的canvas
c.showPage()
#save函数:保存文件并关闭canvas
c.save()

运行结果:

以上这篇Python之ReportLab绘制条形码和二维码的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

详解Python 装饰器执行顺序迷思

探究多个装饰器执行顺序 装饰器是Python用于封装函数或代码的工具,网上可以搜到很多文章可以学习,我在这里要讨论的是多个装饰器执行顺序的一个迷思。 疑问 大部分涉及多个装饰器装饰的...

介绍Python中的fabs()方法的使用

 方法fabs()返回 x 的绝对值。 语法 以下是fabs()方法的语法: import math math.fabs( x ) 注意:此函数是无法直接访问的,所...

Python 使用 prettytable 库打印表格美化输出功能

Python 使用 prettytable 库打印表格美化输出功能

pip install prettytable 每次添加一行 from prettytable import PrettyTable # 默认表头:Field 1、Field 2....

Python3常见函数range()用法详解

0X01函数说明: python range() 函数可创建一个整数列表,一般用在 for 循环中。 0X02函数语法: range(start,stop[,step]) star...

Python 在字符串中加入变量的实例讲解

有时候,我们需要在字符串中加入相应的变量,以下提供了几种字符串加入变量的方法: 1、+ 连字符 name = 'zhangsan' print('my name is '+name...