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)

你可能感兴趣的:(Python,python,reportlab)