python使用reportlab画图示例(含中文汉字)

准备工作

开发环境:python2.6,reportlab

准备中文字体文件:simsun.ttc

代码:

代码如下:

#!/usr/bin/env python2.6#coding:utf-8

import traceback

from reportlab.graphics.shapes import drawingfrom reportlab.graphics.charts.lineplots import lineplotfrom reportlab.graphics.charts.textlabels import labelfrom reportlab.graphics import renderpdffrom reportlab.graphics.widgets.markers import makemarkerfrom reportlab.pdfbase import pdfmetrics, ttfonts

#注意data的类型,#每一个数据点是一个元组#一条曲线对应一个存储数据点元组的元组#一个图形可以包含多条曲线,用列表存储曲线元组data=[((1,100),(2,200),(3,300),(4,400),(5,500)),((1,50),(2,80),(3,400),(4,40),(5,70))]

drawing = drawing(500, 300)

lp = lineplot()lp.x = 50 #坐标轴中心坐标lp.y = 30lp.height = 250lp.width = 400lp.data = datalp.joinedlines = 1lp.lines.symbol = makemarker(‘filledcircle’)

lp.xvalueaxis.valuemin = 1lp.xvalueaxis.valuemax = 5lp.xvalueaxis.valuestep = 1

lp.yvalueaxis.valuemin = 0lp.yvalueaxis.valuemax = 500lp.yvalueaxis.valuestep = 100drawing.add(lp)

title = label()#若需要显示中文,需要先注册一个中文字体pdfmetrics.registerfont(ttfonts.ttfont(“haha”, “simsun.ttc”))title.fontname = “haha”title.fontsize = 12title_text = unicode(‘你好’,’gbk’)#title_text = “abc”title._text = title_texttitle.x = 250title.y = 280title.textanchor =’middle’drawing.add(title)

xlabel = label()xlabel._text = ‘x’xlabel.fontsize = 12xlabel.x = 480xlabel.y = 30xlabel.textanchor =’middle’drawing.add(xlabel)

ylabel = label()ylabel._text = “y”ylabel.fontsize = 12ylabel.x = 40ylabel.y = 295ylabel.textanchor =’middle’drawing.add(ylabel)try: drawing.save(formats=[‘gif’],outdir=”.”,fnroot=”abc”)except: traceback.print_exc()