python reportlab 相对较为可用的正式报表
#coding=utf-8
#from reportlab.lib import *
from reportlab.platypus import *
from reportlab.lib.styles import *
from reportlab.rl_config import *
from reportlab.lib.units import *
from reportlab.lib.pagesizes import *
from reportlab.pdfbase import *
from reportlab.lib import *
#from reportlab.pdfgen import *
from reportlab.graphics.barcode.code39 import *
'''def gather_pdftext (node, depth, in_line_block=False,replaceEnt=True):
for n in node.children:
print n
#return ''.join([for n in node.children ])
class MyParagraph(Paragraph):
def wrap(self, availWidth, availHeight):
self.width = availWidth
leftIndent = self.style.leftIndent
first_line_width = availWidth - (leftIndent+self.style.firstLineIndent) - self.style.rightIndent
later_widths = availWidth - leftIndent - self.style.rightIndent
try:
self.blPara = self.breakLinesCJK([first_line_width, later_widths])
except:
self.blPara = self.breakLines([first_line_width, later_widths])
self.height = len(self.blPara.lines) * self.style.leading
return (self.width,self.height)'''
#Paragraph.wrap = wrap
def init_header_config():
from reportlab.pdfbase.ttfonts import TTFont
import copy
warnOnMissingFontGlyphs = 0
pdfmetrics.registerFont(TTFont('zhenhei','D:/python_workspace/python_pdf_demo/wqy-zenhei.ttc'))
stylesheet= getSampleStyleSheet()
styles= copy.deepcopy(stylesheet['Normal'])
styles.fontName ='zhenhei'
styles.fontSize = 20
return styles
def init_body_font(stylesheet):
import copy
styles= copy.deepcopy(stylesheet['BodyText'])
styles.fontName ='zhenhei'
styles.fontSize = 10
return styles
#首页定义信息
def firstPage(canvas,doc):
TITLE=u"订单打印明细"
canvas.saveState()
canvas.setFont('zhenhei',16)
canvas.drawCentredString(doc.pagesize[0]/2-30,doc.pagesize[1]-40,TITLE)
canvas.setFont('zhenhei',9)
canvas.drawString((doc.pagesize[0]/2)-20,20,u"首页")
# barcode=code39.Extended39("123456789",barWidth=0.5*mm,barHeight=20*mm)
# barcode.drawOn(canvas,100*mm,100*mm)
canvas.restoreState()
#翻页时每页面定义信息
def laterPages(canvas,doc):
TITLE=u"订单打印明细"
canvas.saveState()
canvas.setFont('zhenhei',16)
canvas.drawCentredString(doc.pagesize[0]/2-30,doc.pagesize[1]-40,TITLE)
canvas.setFont('zhenhei', 9)
canvas.drawString((doc.pagesize[0]/2)-20,20,u"页码:%d" % (doc.page))
canvas.restoreState()
def init_data(table_style):
import MySQLdb
hosts='192.168.1.32'
users='root'
passwds='12345'
dbs='shuuemura'
charsets='utf8'
conn=MySQLdb.connect(host=hosts,user=users,passwd=passwds,db=dbs,charset=charsets)
cursor=conn.cursor()
cursor.execute("SELECT PRD_ID,PRD_CODE,PRD_LOCALNAME,PRD_MARKET_PRICE,PRD_COLOR FROM BPRODUCT")
lst=[]
for row in cursor.fetchall():
line=[]
for r in row:
if(r is not None):
pgh=Paragraph(unicode(r),table_style)
#res=pgh.splitLines0(3)
#print dir(pgh)
res=None
try:
res=pgh.breakLinesCJK(40)
except:
res=pgh.breakLines(40)
lstfd=[]
for a in res.lines:
lstfd.append(a[1][0])
ln_str="/n".join(lstfd)
line.append(Paragraph(ln_str,table_style))
#print pgh.blPara.lines
#pgh.wrap(10,100)
#res=pgh.split(10,100)
#print (res[0]).blPara.lines
#print res
#print "..............................."
#line.append(res.lines)
else:
line.append("")
lst.append(line)
cursor.close()
conn.close()
return lst
def init_content():
doc = SimpleDocTemplate("demo4.pdf",pagesize=A4)
#print dir(doc)
#print doc.pagesize[0]
elements=[]
I=Image("logo.jpg")
styleSheet=getSampleStyleSheet()
table_style=init_body_font(styleSheet)
I.drawHeight = 1*inch*I.drawHeight / I.drawWidth
I.drawWidth = 1*inch
P0 = Paragraph('''<b>A pa<font color=red>r</font>a<i>graph</i></b><super><font color=yellow>1</font></super>''',
table_style)
P = Paragraph('''<para align=center spaceb=3>The <b>ReportLab Left<font color=red>Logo</font></b>Image</para>''',
table_style)
data= [['Addddddddfasdfsarwqefksdfsjdfkjsdfkdsf', 'B', 'C', P0, 'D'],
['00', '01', '02', [I,P], '04'],
['10', '11', '12', [P,I], '14'],
[Paragraph(u'测试信息',table_style), '21', '22',Paragraph(u'测试信息',table_style), '24'],
['30', '31', '32', '33', '34']]
dt=init_data(table_style)
lens=len(dt)
pwidth=(doc.pagesize[0]-20)/1000
colwidths = (pwidth*50,pwidth*200,pwidth*400,pwidth*200,pwidth*150)
print pwidth*200
t=Table(dt,colwidths)
#print dir(t)
t.setStyle(TableStyle([('GRID',(0,0),(4,lens),0.25,colors.black)]))
'''t=Table(data,style=[('GRID',(1,1),(-2,-2),1,colors.green),
('BOX',(0,0),(1,-1),2,colors.red),
('LINEABOVE',(1,2),(-2,2),1,colors.blue),
('LINEBEFORE',(2,1),(2,-2),1,colors.pink),
('BACKGROUND', (0, 0), (0, 1), colors.pink),
('BACKGROUND', (1, 1), (1, 2), colors.lavender),
('BACKGROUND', (2, 2), (2, 3), colors.orange),
('BOX',(0,0),(-1,-1),2,colors.black),
('GRID',(0,0),(-1,-1),0.5,colors.black),
('VALIGN',(3,0),(3,0),'BOTTOM'),
('BACKGROUND',(3,0),(3,0),colors.limegreen),
('BACKGROUND',(3,1),(3,1),colors.khaki),
('ALIGN',(3,1),(3,1),'CENTER'),
('BACKGROUND',(3,2),(3,2),colors.beige),
('ALIGN',(3,2),(3,2),'LEFT'),
])'''
# t._argW[3]=1.5*inch
for i in range(10):
elements.append(t)
elements.append(PageBreak())#控制翻页
bc =Standard39()
bc.value = '7S03109120101614B'
elements.append(bc)
doc.build(elements,onFirstPage=laterPages, onLaterPages=laterPages)
#doc.build(elements,onFirstPage=firstPage, onLaterPages=laterPages)
if __name__=="__main__":
init_header_config()
init_content()
#init_data()
===============================================
#coding=utf-8
from django.conf import settings
from django.utils.http import urlquote
from django.template import RequestContext,Context
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from reportlab.platypus import *
from reportlab.lib.styles import *
from reportlab.rl_config import *
from reportlab.lib.units import *
from reportlab.lib import pagesizes,colors
from reportlab.pdfbase import ttfonts,pdfmetrics
import copy
FONT_PATH=('D:/python_workspace/python_pdf_demo/MSYH.TTF',)
class ReportConfig:
#字体初始化
def init_stylesheet(self):
warnOnMissingFontGlyphs = 0
pdfmetrics.registerFont(ttfonts.TTFont('wenquan',FONT_PATH[0]))
stylesheet= getSampleStyleSheet()
return stylesheet
#初始化普通内容字体样式
def init_body_font(self,stylesheet):
body_style=copy.deepcopy(stylesheet["BodyText"])
body_style.fontName="wenquan"
body_style.fontSzie=12
return body_style
def getSplitStr(self,type):
if(type==1):
return "/n"
else:
return "<br/>"
def getSplitParagraph(self,content,width=0,styles=None):
if(width is None or width<=0):
return Paragraph(content,styles)
param=Paragraph(content,styles)
res=None
try:
res=param.breakLinesCJK(width)
except:
res=param.breakLines(width)
lsttmp=[]
for row in res.lines:
lsttmp.append(row[1][0])
#定义换行符
splitstr=self.getSplitStr(2)
tmpstr=splitstr.join(lsttmp)
return Paragraph(tmpstr,styles)
def firstPages(canvas,doc):
TITLE=u"订单信息列表"
canvas.saveState()
canvas.setFont('wenquan',18)
canvas.drawImage("logo.jpg",20,doc.pagesize[1]-35,33,30,[254,255, 254,255, 254,255])
canvas.drawCentredString(doc.pagesize[0]/2-30,doc.pagesize[1]-30,TITLE)
canvas.setFont('wenquan',8)
canvas.drawString((doc.pagesize[0]/2)-20,20,u"第1页")
canvas.restoreState()
def laterPages(canvas,doc):
TITLE=u"订单信息列表"
canvas.saveState()
canvas.setFont('wenquan',18)
canvas.drawImage("logo.jpg",20,doc.pagesize[1]-35,33,30,[254,255, 254,255, 254,255])
canvas.drawCentredString(doc.pagesize[0]/2-30,doc.pagesize[1]-30,TITLE)
canvas.setFont('wenquan',8)
canvas.drawString((doc.pagesize[0]/2)-20,20,u"第%d页" % (doc.page))
canvas.restoreState()
def init_table_data(config,widths,styles):
import MySQLdb
hosts='192.168.1.32'
users='root'
passwds='12345'
dbs='sjpoto'
charsets='utf8'
conn=MySQLdb.connect(host=hosts,user=users,passwd=passwds,db=dbs,charset=charsets)
cursor=conn.cursor()
cursor.execute("SELECT PRD_ID,PRD_CODE,PRD_LOCALNAME,PRD_MARKET_PRICE,PRD_COLOR FROM BPRODUCT")
lst=[]
for row in cursor.fetchall():
lines=[]
i=0
for field in row:
if(field is not None):
lines.append(config.getSplitParagraph(unicode(field),widths[i],styles))
else:
lines.append("")
i=i+1
lst.append(lines)
cursor.close()
conn.close()
return lst
def init_content():
doc=SimpleDocTemplate("demo5.pdf",pagesize=pagesizes.A4)
config=ReportConfig()
elements=[]
stylesheet=config.init_stylesheet()
content_style=config.init_body_font(stylesheet)
#p=config.getSplitParagraph(u"测试werqwerwe细3421341234234234心你",20,content_style)
#elements.append(p)
#将页面总宽度分成1000份,取其中1份
pwidth=(doc.pagesize[0]-20)/1000
#表格每列宽度,总共5列
colwidths = (pwidth*50,pwidth*200,pwidth*400,pwidth*200,pwidth*150)
table_data=init_table_data(config,colwidths,content_style)
table1=Table(table_data,colwidths)
table1.setStyle(TableStyle([('GRID',(0,0),(4,len(table_data)),0.25,colors.black)]))
elements.append(table1)
#强制分页
#elements.append(PageBreak())
#再添加一个table
data2=[["aaaa","bbbbbbbbbbbb","cccccccccccccc","ddddddddddddd"],]
colwidths = (pwidth*250,pwidth*250,pwidth*250,pwidth*250)
table2=Table(data2,colwidths)
table2.setStyle(TableStyle([('GRID',(0,0),(4,len(data2)),0.25,colors.black)]))
elements.append(table2)
#生称报表最终内容
#doc.build(elements,onFirstPage=firstPages)
doc.build(elements,onFirstPage=firstPages, onLaterPages=laterPages)
def index(request):
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'
doc=SimpleDocTemplate(response,pagesize=pagesizes.A4)
config=ReportConfig()
elements=[]
stylesheet=config.init_stylesheet()
content_style=config.init_body_font(stylesheet)
#p=config.getSplitParagraph(u"测试werqwerwe细3421341234234234心你",20,content_style)
#elements.append(p)
#将页面总宽度分成1000份,取其中1份
pwidth=(doc.pagesize[0]-20)/1000
#表格每列宽度,总共5列
colwidths = (pwidth*50,pwidth*200,pwidth*400,pwidth*200,pwidth*150)
table_data=init_table_data(config,colwidths,content_style)
table1=Table(table_data,colwidths)
table1.setStyle(TableStyle([('GRID',(0,0),(4,len(table_data)),0.25,colors.black)]))
elements.append(table1)
#强制分页
#elements.append(PageBreak())
#再添加一个table
data2=[["aaaa","bbbbbbbbbbbb","cccccccccccccc","ddddddddddddd"],]
colwidths = (pwidth*250,pwidth*250,pwidth*250,pwidth*250)
table2=Table(data2,colwidths)
table2.setStyle(TableStyle([('GRID',(0,0),(4,len(data2)),0.25,colors.black)]))
elements.append(table2)
#生称报表最终内容
#doc.build(elements,onFirstPage=firstPages)
doc.build(elements,onFirstPage=firstPages, onLaterPages=laterPages)
return response
posted on 2010-03-22 12:06 reck for zhou 阅读(1308) 评论(0) 编辑 收藏 举报