翼度科技»论坛 编程开发 python 查看内容

python中的Reportlab模块详解最新推荐

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
python中的Reportlab模块

reportlab模块是用python语言生成pdf文件的模块
安装:pip install reportlab
模块默认不支持中文,如果使用中文需要注册

1.注册中文字体

下载自己需要的.ttf字体,例如STSONG.ttf
fromreportlab.pdfbaseimportpdfmetrics
fromreportlab.pdfbase.ttfontsimportTTFont
pdfmetrics.registerFont(TTFont('song', STSONG.ttf))

2.生成文字
  1. from reportlab.lib.styles import getSampleStyleSheet
  2. from reportlab.platypus import Paragraph,SimpleDocTemplate
  3. from reportlab.lib import  colors
  4. Style=getSampleStyleSheet()
  5. bt = Style['Normal']     #字体的样式
  6. # bt.fontName='song'    #使用的字体
  7. bt.fontSize=14            #字号
  8. bt.wordWrap = 'CJK'    #该属性支持自动换行,'CJK'是中文模式换行,用于英文中会截断单词造成阅读困难,可改为'Normal'
  9. bt.firstLineIndent = 32  #该属性支持第一行开头空格
  10. bt.leading = 20             #该属性是设置行距
  11. ct=Style['Normal']
  12. # ct.fontName='song'
  13. ct.fontSize=12
  14. ct.alignment=1             #居中
  15. ct.textColor = colors.red
  16. t = Paragraph('hello',bt)
  17. pdf=SimpleDocTemplate('ppff.pdf')
  18. pdf.multiBuild([t])
复制代码

一份pdf文件可以定义多种字体样式,如bt和ct。字体有多种属性,这里只列举一些常用的属性,
其中,
wordWrap自动换行属性的参数'CJK'是按照中文方式换行(可以在字符之间换行),英文方式为'Normal'(在空格出换行)
alignment:0 左对齐
       1 居中
       2 右对齐

3.表格

from reportlab.platypus import Table
t = Table(data)
  1. from reportlab.platypus import Paragraph, SimpleDocTemplate, Table,TableStyle
  2. from reportlab.lib.units import inch
  3. from reportlab.lib import colors
  4. def table_model(data):
  5.     width = 7.2  # 总宽度
  6.     colWidths = (width / len(data[0])) * inch   # 每列的宽度
  7.     dis_list = []
  8.     for x in data:
  9.         # dis_list.append(map(lambda i: Paragraph('%s' % i, cn), x))
  10.         dis_list.append(x)
  11.     style = [
  12.         # ('FONTNAME', (0, 0), (-1, -1), 'song'),  # 字体
  13.         ('FONTSIZE', (0, 0), (-1, 0), 15),  # 字体大小
  14.         ('BACKGROUND', (0, 0), (-1, 0), HexColor('#d5dae6')),  # 设置第一行背景颜色
  15.         ('BACKGROUND', (0, 1), (-1, 1), HexColor('#d5dae6')),  # 设置第二行背景颜色
  16.         # 合并 ('SPAN',(第一个方格的左上角坐标),(第二个方格的左上角坐标)),合并后的值为靠上一行的值,按照长方形合并
  17.         ('SPAN',(0,0),(0,1)),
  18.         ('SPAN',(1,0),(2,0)),
  19.         ('SPAN',(3,0),(4,0)),
  20.         ('SPAN',(5,0),(7,0)),
  21.         ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 对齐
  22.         ('VALIGN', (-1, 0), (-2, 0), 'MIDDLE'),  # 对齐
  23.         ('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey),  # 设置表格左边线颜色为灰色,线宽为0.1
  24.         ('TEXTCOLOR', (0, 0), (-1, 0), colors.royalblue),  # 设置表格内文字颜色
  25.         ('TEXTCOLOR', (0, -1), (-1, -1), colors.red),  # 设置表格内文字颜色
  26.         ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),  # 设置表格框线为grey色,线宽为0.5
  27.     ]
  28.     component_table = Table(dis_list, colWidths=colWidths,style=style)
  29.     return component_table
  30. Style=getSampleStyleSheet()
  31. n = Style['Normal']
  32. data = [[0,1,2,3,4,5,6,7],
  33.         [00,11,22,33,44,55,66,77],
  34.         [000,111,222,333,444,555,666,777],
  35.         [0000,1111, 2222, 3333, 4444, 5555, 6666, 7777],]
  36. z = table_model(data)
  37. pdf = MyDocTemplate('ppff.pdf')
  38. pdf.multiBuild([Paragraph('Title',n),z])
复制代码


4.添加边框

from reportlab.graphics.shapes import Drawing
d = Drawing()
参数有:
d.width:边框宽度
d.heigth:边框高度
d.background:边框颜色
等等。
边框中可使用add()添加文字,图形等内容
例:
在边框中添加文字
  1. from reportlab.graphics.shapes import Drawing, Rect
  2. from reportlab.graphics.charts.textlabels import Label
  3. def autoLegender( title=''):
  4.     width = 448
  5.     height = 230
  6.     d = Drawing(width,height)
  7.     lab = Label()
  8.     lab.x = 220  #x和y是文字的位置坐标
  9.     lab.y = 210
  10.     lab.setText(title)
  11.     # lab.fontName = 'song' #增加对中文字体的支持
  12.     lab.fontSize = 20
  13.     d.add(lab)
  14.     d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor="#868686",fillColor=None) #边框颜色
  15.     return d
  16. l = autoLegender('hello')
  17. pdf=SimpleDocTemplate('ppff.pdf')
  18. pdf.multiBuild([l])
复制代码
  1. # **这种方法可以给边框中的图例添加颜色说明**
  2. def autoLegender(chart, categories=[], use_colors=[], title=''):
  3.     width = 448
  4.     height = 230
  5.     d = Drawing(width,height)
  6.     lab = Label()
  7.     lab.x = 220  #x和y是title文字的位置坐标
  8.     lab.y = 210
  9.     lab.setText(title)
  10.     # lab.fontName = 'song' #增加对中文字体的支持
  11.     lab.fontSize = 20
  12.     d.add(lab)
  13.     d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor="#868686",fillColor=None) #边框颜色
  14.     d.add(chart)
  15.     #颜色图例说明等
  16.     leg = Legend()
  17.     leg.x = 500   # 说明的x轴坐标
  18.     leg.y = 0     # 说明的y轴坐标
  19.     leg.boxAnchor = 'se'
  20.     # leg.strokeWidth = 4
  21.     leg.strokeColor = None
  22.     leg.subCols[1].align = 'right'
  23.     leg.columnMaximum = 10  # 图例说明一列最多显示的个数
  24. # leg.fontName = 'song' leg.alignment = 'right' leg.colorNamePairs = zip(use_colors, tuple(categories)) #增加颜色说明 d.add(leg) return d
复制代码


5.饼状图

饼图需要添加在边框中
  1. from reportlab.lib import colors
  2. from reportlab.platypus import SimpleDocTemplate
  3. from reportlab.graphics.shapes import Drawing, Rect
  4. from reportlab.graphics.charts.textlabels import Label
  5. from reportlab.graphics.charts.piecharts import Pie
  6. def autoLegender( chart,title=''):
  7.     width = 448
  8.     height = 230
  9.     d = Drawing(width,height)
  10.     lab = Label()
  11.     lab.x = 220  #x和y是文字的位置坐标
  12.     lab.y = 210
  13.     lab.setText(title)
  14.     # lab.fontName = 'song' #增加对中文字体的支持
  15.     lab.fontSize = 20
  16.     d.add(lab)
  17.     d.background = Rect(0,0,width,height,strokeWidth=1,strokeColor="#868686",fillColor=None) #边框颜色
  18.     d.add(chart)
  19.     return d
  20. def draw_pie(data=[], labels=[], use_colors=[], width=360,):
  21.     '''更多属性请查询reportlab.graphics.charts.piecharts.WedgeProperties'''
  22.     pie = Pie()
  23.     pie.x = 60 # x,y饼图在框中的坐标
  24.     pie.y = 20
  25.     pie.slices.label_boxStrokeColor = colors.white  #标签边框的颜色
  26.     pie.data = data      # 饼图上的数据
  27.     pie.labels = labels  # 数据的标签
  28.     pie.simpleLabels = 0 # 0 标签在标注线的右侧;1 在线上边
  29.     pie.sameRadii = 1    # 0 饼图是椭圆;1 饼图是圆形
  30.     pie.slices.strokeColor = colors.red       # 圆饼的边界颜色
  31.     pie.strokeWidth=1                         # 圆饼周围空白区域的宽度
  32.     pie.strokeColor= colors.white             # 整体饼图边界的颜色
  33.     pie.slices.label_pointer_piePad = 10       # 圆饼和标签的距离
  34.     pie.slices.label_pointer_edgePad = 25    # 标签和外边框的距离
  35.     pie.width = width
  36.     pie.direction = 'clockwise'
  37.     pie.pointerLabelMode  = 'LeftRight'
  38.     # for i in range(len(labels)):
  39.     #     pie.slices[i].fontName = 'song' #设置中文
  40.     for i, col in enumerate(use_colors):
  41.          pie.slices[i].fillColor  = col
  42.     return pie
  43. data = [10,9,8,7,6,5,4,3,2,1]
  44. labs = ['0000000','1111111','2222222','3333333','4444444',
  45.         '5555555','6666666','7777777','8888888','9999999']
  46. color = [HexColor("#696969"),HexColor("#A9A9A9"),HexColor("#D8BFD8"),
  47.          HexColor("#DCDCDC"),HexColor('#E6E6FA'),HexColor("#B0C4DE"),
  48.          HexColor("#778899"),HexColor('#B0C4DE'),HexColor("#6495ED"),
  49.          HexColor("#483D8B")
  50.          ]
  51. z = autoLegender(draw_pie(data,labs,color),labs,color)
  52. pdf=SimpleDocTemplate('ppff.pdf')
  53. pdf.multiBuild([z])
复制代码


6.柱状图

柱状图需要添加在边框中
  1. from reportlab.graphics.charts.barcharts import VerticalBarChart
  2. from reportlab.lib.colors import HexColor
  3. def draw_bar_chart(min, max, x_list, data=[()], x_label_angle=0, bar_color=HexColor("#7BB8E7"), height=125, width=280):
  4.     '''
  5.     :param min: 设置y轴的最小值
  6.     :param max: 设置y轴的最大值
  7.     :param x_list: x轴上的标签
  8.     :param data: y轴对应标签的值
  9.     :param x_label_angle: x轴上标签的倾斜角度
  10.     :param bar_color: 柱的颜色  可以是含有多种颜色的列表
  11.     :param height: 柱状图的高度
  12.     :param width: 柱状图的宽度
  13.     :return:
  14.     '''
  15.     bc = VerticalBarChart()
  16.     bc.x = 50            # x和y是柱状图在框中的坐标
  17.     bc.y = 50
  18.     bc.height = height  # 柱状图的高度
  19.     bc.width = width    # 柱状图的宽度
  20.     bc.data = data      
  21.     for j in xrange(len(x_list)):
  22.         setattr(bc.bars[j], 'fillColor', bar_color)  # bar_color若含有多种颜色在这里分配bar_color[j]
  23.     # 调整step
  24.     minv = min * 0.5
  25.     maxv = max * 1.5
  26.     maxAxis = int(height/10)
  27.     # 向上取整
  28.     minStep = int((maxv-minv+maxAxis-1)/maxAxis)
  29.     bc.valueAxis.valueMin = min * 0.5      #设置y轴的最小值
  30.     bc.valueAxis.valueMax = max * 1.5      #设置y轴的最大值
  31.     bc.valueAxis.valueStep = (max-min)/4   #设置y轴的最小度量单位
  32.     if bc.valueAxis.valueStep < minStep:
  33.         bc.valueAxis.valueStep = minStep
  34.     if bc.valueAxis.valueStep == 0:
  35.         bc.valueAxis.valueStep = 1
  36.     bc.categoryAxis.labels.boxAnchor = 'ne'   # x轴下方标签坐标的开口方向
  37.     bc.categoryAxis.labels.dx = -5           # x和y是x轴下方的标签距离x轴远近的坐标
  38.     bc.categoryAxis.labels.dy = -5
  39.     bc.categoryAxis.labels.angle = x_label_angle   # x轴上描述文字的倾斜角度
  40.     # bc.categoryAxis.labels.fontName = 'song'
  41.     x_real_list = []
  42.     if len(x_list) > 10:
  43.         for i in range(len(x_list)):
  44.             tmp = '' if i%5 != 0 else x_list[i]
  45.             x_real_list.append(tmp)
  46.     else:
  47.         x_real_list = x_list
  48.     bc.categoryAxis.categoryNames = x_real_list
  49.     return bc
  50. z = autoLegender(draw_bar_chart(100, 300, ['a', 'b', 'c'], [(100, 200, 120)]))
  51. pdf=SimpleDocTemplate('ppff.pdf')
  52. pdf.multiBuild([z])
复制代码


6.累加柱状图
  1. def draw_2bar_chart(min, max, x_list, data=[()],array=[()], x_label_angle=0,bar_color=[],height=125, width=280):
  2.     '''
  3.     :param min: 设置y轴的最小值
  4.     :param max: 设置y轴的最大值
  5.     :param x_list: x轴上的标签
  6.     :param data: y轴对应标签的值
  7.     :param x_label_angle: x轴上标签的倾斜角度
  8.     :param bar_color: 柱的颜色  可以是含有多种颜色的列表
  9.     :param height: 柱状图的高度
  10.     :param width: 柱状图的宽度
  11.     :return:
  12.     '''
  13.     bc = VerticalBarChart()
  14.     bc.x = 50            # x和y是柱状图在框中的坐标
  15.     bc.y = 50
  16.     bc.height = height  # 柱状图的高度
  17.     bc.width = width    # 柱状图的宽度
  18.     bc.data = data
  19.     # 图形柱上标注文字
  20.     bc.barLabels.nudge = -5  # 文字在图形柱的上下位置
  21.     bc.barLabelArray = array  # 要添加的文字
  22.     bc.barLabelFormat = 'values'
  23.     for j in xrange(len(data)):
  24.         setattr(bc.bars[j], 'fillColor', bar_color[j])  # bar_color若含有多种颜色在这里分配bar_color[j]
  25.     # 调整step
  26.     # minv = min * 0.5
  27.     minv = 0
  28.     maxv = max * 1.5
  29.     maxAxis = int(height/10)
  30.     # 向上取整
  31.     minStep = int((maxv-minv+maxAxis-1)/maxAxis)
  32.     bc.valueAxis.valueMin =0      #设置y轴的最小值
  33.     bc.valueAxis.valueMax = max * 1.5      #设置y轴的最大值
  34.     bc.valueAxis.valueStep = (max-min)/4   #设置y轴的最小度量单位
  35.     if bc.valueAxis.valueStep < minStep:
  36.         bc.valueAxis.valueStep = minStep
  37.     if bc.valueAxis.valueStep == 0:
  38.         bc.valueAxis.valueStep = 1
  39.     bc.categoryAxis.labels.boxAnchor = 'ne'   # x轴下方标签坐标的开口方向
  40.     bc.categoryAxis.labels.dx = -5           # x和y是x轴下方的标签距离x轴远近的坐标
  41.     bc.categoryAxis.labels.dy = -5
  42.     bc.categoryAxis.labels.angle = x_label_angle   # x轴上描述文字的倾斜角度
  43.     # bc.categoryAxis.labels.fontName = 'song'
  44.     bc.categoryAxis.style = 'stacked'
  45.     x_real_list = []
  46.     if len(x_list) > 10:
  47.         for i in range(len(x_list)):
  48.             tmp = '' if i%5 != 0 else x_list[i]
  49.             x_real_list.append(tmp)
  50.     else:
  51.         x_real_list = x_list
  52.     bc.categoryAxis.categoryNames = x_real_list
  53.     return bc
  54. #    制柱状图
  55. Style=getSampleStyleSheet()
  56. n = Style['Normal']
  57. my_color = [HexColor('#E13C3C'),HexColor('#BE0000')]
  58. z = autoLegender(draw_2bar_chart(100, 300, ['a', 'b', 'c'],
  59.                                 [(100, 200, 120),(150, 50, 130)],
  60.                                 bar_color=my_color,
  61.                                 array=[['100','200','120'],['150','50','130']] ),
  62.                  categories=['first','last'],
  63.                  use_colors=my_color
  64.                  )
  65. pdf = MyDocTemplate('ppff.pdf')
  66. pdf.multiBuild([Paragraph('Title',n),z])
复制代码


7.添加页眉

添加页眉需要我们自定义模版
  1. from reportlab.platypus.doctemplate import BaseDocTemplate, Frame
  2. from reportlab.lib.units import cm
  3. from reportlab.platypus import PageTemplate
  4. from reportlab.lib.styles import getSampleStyleSheet
  5. import os
  6. def myMainPageFrame(canvas, doc):  # 全局应用
  7.     "The page frame used for all PDF documents."
  8.     canvas.saveState()
  9.     canvas.setFont('Times-Roman', 12)
  10.     pageNumber = canvas.getPageNumber()
  11.     if pageNumber > 0:
  12.         pic_yemei = os.path.join(os.path.dirname(__file__),'yemei01.jpg')   # 页眉图片
  13.         pic_line_file = os.path.join(os.path.dirname(__file__),'line.jpg')  # 页眉线
  14.         canvas.drawImage(pic_yemei, 75, 795, width=100,height=25)
  15.         canvas.drawImage(pic_line_file, 75, 780, width=450, height=15)
  16.         canvas.drawString(10*cm, cm, str(pageNumber))
  17.     canvas.restoreState()
  18. class MyDocTemplate(BaseDocTemplate):  # 自定义模版类
  19.     "The document template used for all PDF documents."
  20.     _invalidInitArgs = ('pageTemplates',)
  21.     def __init__(self, filename, **kw):
  22.         frame1 = Frame(2.5*cm, 2.5*cm, 15*cm, 25*cm, id='F1')
  23.         self.allowSplitting = 0
  24.         BaseDocTemplate.__init__(self, filename, **kw)
  25.         template = PageTemplate('normal', [frame1], myMainPageFrame)
  26.         self.addPageTemplates(template)   # 绑定全局应用
  27. Style=getSampleStyleSheet()
  28. n = Style['Normal']
  29. z = autoLegender(draw_bar_chart(100, 300, ['a', 'b', 'c'], [(100, 200, 120)]))
  30. pdf = MyDocTemplate('ppff.pdf')
  31. pdf.multiBuild([Paragraph('Title',n),z])
复制代码
到此这篇关于python中的Reportlab模块的文章就介绍到这了,更多相关python Reportlab内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/283877.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具