python reportlab生成pdf
添加页码,支持中文
·
简单的添加页码。支持中文的方法
from reportlab.lib.pagesizes import A4, landscape, portrait
from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
from reportlab.platypus import Table, Flowable, SimpleDocTemplate,Paragraph, Spacer, Image
from reportlab.lib import randomtext
from reportlab import platypus
from reportlab.pdfgen import canvas
import os,random
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
# https://github.com/StellarCN/scp_zh/tree/master/fonts 复制到这里“site-packages\reportlab\fonts”
pdfmetrics.registerFont(TTFont('SimHei', 'SimHei.TTF'))
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf')) #注册字体
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(fontName='SimSun', name='SimSun', leading=20, fontSize=12)) #自己增加新注册的字体
story = []
#add some flowables
def drawPageFrame(canvas, doc,pagesize=A4):
canvas.saveState()
page_num = canvas.getPageNumber()
canvas.drawCentredString(pagesize[0]/2, 50, str(page_num))
canvas.drawImage("./python_logo.png",50,50,57,57)
canvas.restoreState()
doc = SimpleDocTemplate("salida.pdf",pagesize=A4)
story = []
com = 'canvas.drawImage("./python_logo.png",100,100,57,57)'
print (com)
story.append(platypus.flowables.Macro('canvas.saveState()'))
print (platypus.flowables.Macro(com))
story.append(platypus.flowables.Macro(com))
story.append(platypus.flowables.Macro('canvas.restoreState()'))
para = Paragraph(randomtext.randomText(randomtext.PYTHON,20),styles["Normal"])
para2 = Paragraph(randomtext.randomText(randomtext.COMPUTERS,20),styles["Normal"])
para3 = Paragraph(randomtext.randomText(randomtext.STARTREK,20),styles["Normal"])
story.append(Paragraph("中文支持",styles['SimSun']))
story.append(para)
story.append(Spacer(1, 12))
story.append(para2)
story.append(Spacer(1, 100))
story.append(para3)
doc.build(story,onFirstPage=drawPageFrame, onLaterPages=drawPageFrame)
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献5条内容
所有评论(0)