Python3操作pdf文件之ReportLab的居中与换行

昨天,就在昨天,咱用了用ReportLab,那效果真的好得不得了,可惜因为篇幅问题,只是小刀牛试了一把,在解决了它的中文问题后,就戛然而止了,甚是寡淡无味。

为了让Python3处理pdf的口味更重一些,咱就来给ReportLab添点料。

1

这次要实现的功能,主要是标题和一段文字的描述,这么有用的功能就问你惊不惊喜,意不意外。有关标题的功能,你可千万别小瞧了,单是居中,就有很多人不知道怎么实现才好。好了,别只顾兴奋了,咱开始搬砖吧。

from reportlab.pdfbase import pdfmetrics

from reportlab.pdfbase.ttfonts import TTFont

from reportlab.platypus import SimpleDocTemplate, Paragraph

from reportlab.lib.pagesizes import letter

from reportlab.lib.styles import getSampleStyleSheet

from reportlab.lib import colors



# 注册字体

pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))



class Graphs:

 def __init__(self):

 pass


 # 绘制标题

 @staticmethod

 def draw_title():

 style = getSampleStyleSheet()

 ct = style['Normal']

 ct.fontName = 'SimSun'

 ct.fontSize = 18

 # 设置行距

 ct.leading = 50

 # 颜色

 ct.textColor = colors.green

 # 居中

 ct.alignment = 1

 # 添加标题并居中

 title = Paragraph('程序员的兴趣调查报告', ct)

 return title



if __name__ == "__main__":

 content = list()

 # 添加标题

 content.append(Graphs.draw_title())

 # 生成pdf文件

 doc = SimpleDocTemplate('report.pdf', pagesize=letter)

 doc.build(content)

2

如果只是有个标题,总感觉很沙雕似的。行,那咱就再来一段内容,让内容更炫实,更丰富一些。这里的段落内容换行,也是大家经常寻找的答案,我写好了,拿走不谢。好了,别只顾兴奋了,咱还得继续搬砖。

from reportlab.pdfbase import pdfmetrics

from reportlab.pdfbase.ttfonts import TTFont

from reportlab.platypus import SimpleDocTemplate, Paragraph

from reportlab.lib.pagesizes import letter

from reportlab.lib.styles import getSampleStyleSheet

from reportlab.lib import colors



# 注册字体

pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))



class Graphs:

 def __init__(self):

 pass


 # 绘制标题

 @staticmethod

 def draw_title():

    style = getSampleStyleSheet()

 ct = style['Normal']

 ct.fontName = 'SimSun'

 ct.fontSize = 18

 # 设置行距

 ct.leading = 50

 # 颜色

 ct.textColor = colors.green

 # 居中

 ct.alignment = 1

 # 添加标题并居中

 title = Paragraph('程序员的兴趣调查报告', ct)

 return title


 # 绘制内容

 @staticmethod

 def draw_text():

 style = getSampleStyleSheet()

 # 常规字体(非粗体或斜体)

 ct = style['Normal']

 # 使用的字体s

 ct.fontName = 'SimSun'

 ct.fontSize = 14

 # 设置自动换行

 ct.wordWrap = 'CJK'

 # 居左对齐

 ct.alignment = 0

 # 第一行开头空格

 ct.firstLineIndent = 32

 # 设置行距

 ct.leading = 30

 text = Paragraph('程序员,是互联网、移动互联网和即将到来的物联网时期的弄潮儿。这群特立独行的人才,不知平时最喜欢什么?他们的兴趣真想让人一探究竟。经过七七49天的调研,终于形成了一份不具备权威性的统计报告,现公布给大家。', ct)

 return text



if __name__ == "__main__":

 content = list()

 # 添加标题

 content.append(Graphs.draw_title())

 # 添加段落

 content.append(Graphs. draw_text ())

 # 生成pdf文件

 doc = SimpleDocTemplate('report.pdf', pagesize=letter)

 doc.build(content)

你可能感兴趣的:(Python3操作pdf文件之ReportLab的居中与换行)