本人初步学习Python,用python的第一个项目就是 生成报告,先将代码贴上,以后将我的心得写一下,以避免大家再次踩坑
#coding: utf-8
# from LaserDB import LaserDB
import sys
if 'threading' in sys.modules:
del sys.modules['threading']
import sqlite3 as db
import os
import json
import re
import matplotlib.pyplot as plt
from matplotlib import font_manager
# cn_font = 'Droid Sans Fallback'
cn_font = font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/uming.ttc')
# cn_font = font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/ukai.ttc')
import cStringIO
from reportlab.lib.utils import ImageReader
import time
from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY,TA_CENTER
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, cm, mm
import reportlab.rl_config
reportlab.rl_config.warnOnMissingFontGlyphs = 0
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
from reportlab.lib import fonts
fonts.addMapping('STSong-Light', 0, 0, 'STSong-Light')
fonts.addMapping('STSong-Light', 0, 1, 'STSong-Light')
fonts.addMapping('STSong-Light', 1, 0, 'STSong-Light')
fonts.addMapping('STSong-Light', 1, 1, 'STSong-Light')
from reportlab.rl_config import defaultPageSize
PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]
import copy
import datetime
frameNum = 0
laserNum = 0
pdfTitle_name = {}
DBfile_name = {}
outputfile_name = {}
LidarId = {}
LidarName = {}
time = {}
testPeople = {}
distance = {}
lidarIntensity = {}
temperature = {}
boardMapList = {}
story=[]
distSet = []
dataValue = []
ispass = 1
# Font format
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
styles.add(ParagraphStyle(name='Center-green', alignment=TA_CENTER,textColor=colors.green))
styles.add(ParagraphStyle(name='Center-red', alignment=TA_CENTER,textColor=colors.red))
styles.add(ParagraphStyle(name='green',textColor=colors.green))
styles.add(ParagraphStyle(name='red',textColor=colors.red))
styles.add(ParagraphStyle(name='black',textColor=colors.black))
styles.add(ParagraphStyle(name='Center-black',alignment=TA_CENTER,textColor=colors.black))
styles.add(ParagraphStyle(name='FirstTitle', alignment=TA_CENTER))
styles.add(ParagraphStyle(name='SecondTitle', alignment=0))
styles.add(ParagraphStyle(name='ThirdTitle', alignment=0,leftIndent=24))
# Place the points in the database into this class.
class distanceData:
def __init__(self, laser, maxdistance,avgdistance,mindistance ,temperature,threshold, intensity, ispass):
self.laser = laser
self.maxdistance = maxdistance
self.avgdistance = avgdistance
self.mindistance = mindistance
self.temperature = temperature
self.threshold = threshold
self.intensity = intensity
self.ispass = ispass
# add page number function
def addExtraInfo(canvas, doc):
'''
Add the page number
'''
page_num = canvas.getPageNumber()
text = "-%s-" % page_num
canvas.drawCentredString(PAGE_WIDTH/2.0, 20*mm, text)
# set tab title for pdf
canvas.setTitle("Hesaitech")
styleSheet = getSampleStyleSheet()
style = styleSheet['BodyText']
corner=Paragraph('''<a href="#page1">%s</a>''' % u'\u2191',style)
w,h = corner.wrapOn(canvas, 10*mm, 10*mm)
def parserDB(db_filename,db_tablename):
conn = db.connect(db_filename) # 该 API 打开一个到 SQLite 数据库文件 database 的链接,如果数据库成功打开,则返回一个连接对象
cur=conn.cursor() # 该例程创建一个 cursor,将在 Python 数据库编程中用到。
conn.row_factory=db.Row # 可访问列信息
tableName = "select * from " + db_tablename
cur.execute(tableName) # 该例程执行一个 SQL 语句
#cur.execute("select * from wave_distance") # 该例程执行一个 SQL 语句
rows=cur.fetchall() # 该例程获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表。
return rows
# generate the wave report
def WaveReportchart(db_filename,db_tablename,tableTitle):
global laserNum
global dataValue
global ispass
ispass = 1;
# chart pdf the first page
# the chart header
CNStyle = copy.deepcopy(styles['Center'])
CNStyle.fontName ='STSong-Light'
story.append(Paragraph('<font size=15><a name="page1"/>%s</font>'%(tableTitle),CNStyle))
story.append(Spacer(1, 15))
component_data = []
ChartLine = []
ChartSecondLine = []
partDataValue = []
# Set the table head
ChartLine.append(Paragraph('<font>通道</font>',CNStyle))
ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))
ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))
ChartLine.append(Paragraph('<font>测距能力(米)</font>',CNStyle))
ChartLine.append(Paragraph('<font>测距下限\n(米)</font>',CNStyle))
ChartLine.append(Paragraph('<font>反射率\n(%)</font>',CNStyle))
ChartLine.append(Paragraph('<font>测试温度\n(℃)</font>',CNStyle))
ChartLine.append(Paragraph('<font>是否通过\n(平均值)</font>',CNStyle))
component_data.append(ChartLine)
ChartSecondLine.append(Paragraph('<font></font>',CNStyle))
ChartSecondLine.append(Paragraph('<font>最大值</font>',CNStyle))
ChartSecondLine.append(Paragraph('<font>平均值</font>',CNStyle))
ChartSecondLine.append(Paragraph('<font>最小值</font>',CNStyle))
ChartSecondLine.append(Paragraph('<font></font>',CNStyle))
ChartSecondLine.append(Paragraph('<font></font>',CNStyle))
ChartSecondLine.append(Paragraph('<font></font>',CNStyle))
ChartSecondLine.append(Paragraph('<font></font>',CNStyle))
component_data.append(ChartSecondLine)
#parser database and place data to the point class
lines = parserDB(db_filename,db_tablename)
for line in lines:
value = [s for s in line]
oneline = distanceData(value[0],value[1],value[3],value[2],value[4],value[5],value[6],int(value[7]))
partDataValue.append(oneline)
dataValue = partDataValue
#Arranging data into rows and rows of information
for oneChannel in dataValue:
partLaserValue = []
if (oneChannel.ispass == 0):
result = "fail"
typeFace = "Center-red"
ispass = 0
else:
result = "pass"
typeFace = "Center-black"
if (int(oneChannel.avgdistance) == 0):
avgdistance_result = "Unmeasurable"
else:
avgdistance_result = oneChannel.avgdistance
if (int(oneChannel.maxdistance) == 0):
maxdistance_result = "Unmeasurable"
else:
maxdistance_result = oneChannel.maxdistance
if (int(oneChannel.mindistance) == 0):
mindistance_result = "Unmeasurable"
else:
mindistance_result = oneChannel.mindistance
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (oneChannel.laser),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (maxdistance_result),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (avgdistance_result),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (mindistance_result),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (oneChannel.threshold),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (oneChannel.intensity),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' % (oneChannel.temperature),
styles[typeFace]))
partLaserValue.append(Paragraph('''
<font size=8>%s</font>''' %(result),
styles[typeFace]))
component_data.append(partLaserValue);
# Set tabular format
component_table = Table(component_data, colWidths=65)
component_table.setStyle(TableStyle([('FONTSIZE', (-1, -1), (-2, -2), 10),
('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey),
('SPAN',(1,0),(3,0)),
('SPAN',(0,1),(0,0)),
('SPAN',(4,1),(4,0)),
('SPAN',(5,1),(5,0)),
('SPAN',(6,1),(6,0)),
('SPAN',(7,1),(7,0)),
('GRID', (0, 0), (-1, -1), 0.5, colors.black)]))
if (ispass == 0):
CNStyle = copy.deepcopy(styles['red'])
CNStyle.fontName ='STSong-Light'
story.append(Paragraph('<font size=15>测试结果:fail</font>',CNStyle))
else:
CNStyle = copy.deepcopy(styles['green'])
CNStyle.fontName ='STSong-Light'
story.append(Paragraph('<font size=15>测试结果:pass</font>',CNStyle))
story.append(Spacer(1, 15))
story.append(component_table)
story.append(PageBreak())
# add pdf title
def pdfTitle(LidarName):
CNStyle = copy.deepcopy(styles['Center'])
CNStyle.fontName ='STSong-Light'
story.append(Paragraph('<font size=25><a name="page1"/>%s 测远能力报告</font>'%(LidarName) ,CNStyle))
story.append(Spacer(1, 50))
def pdfBasicInfomation():
global LidarId
global LidarName
global testPeople
global distance
global lidarIntensity
global temperature
timeDate = datetime.datetime.now().strftime('%Y-%m-%d')
timeNow = datetime.datetime.now().strftime('%H:%M:%S')
firstLine = [];
secondLine = [];
thirdLine = [];
fourthLine = [];
component_data = []
CNStyle = copy.deepcopy(styles['Center'])
CNStyle.fontName ='STSong-Light'
story.append(Paragraph('<font size=15><a name="page1"/>测试基本信息</font>',CNStyle))
story.append(Spacer(1, 15))
firstLine.append(Paragraph('<font size=10>Lidar编号</font>',CNStyle))
firstLine.append(Paragraph('<font size=10>Lidar型号</font>',CNStyle))
firstLine.append(Paragraph('<font size=10>测试日期</font>',CNStyle))
firstLine.append(Paragraph('<font size=10>生成报告时间</font>',CNStyle))
component_data.append(firstLine)
secondLine.append(Paragraph('<font size=10>%s</font>'%(LidarId),CNStyle))
secondLine.append(Paragraph('<font size=10>%s</font>'%(LidarName),CNStyle))
secondLine.append(Paragraph('<font size=10>%s</font>'%(timeDate),CNStyle))
secondLine.append(Paragraph('<font size=10>%s</font>'%(timeNow),CNStyle))
component_data.append(secondLine)
thirdLine.append(Paragraph('<font size=10>靶板距离(m)</font>',CNStyle))
thirdLine.append(Paragraph('<font size=10>靶板反射率(%)</font>',CNStyle))
thirdLine.append(Paragraph('<font size=10>测试温度(℃)</font>',CNStyle))
thirdLine.append(Paragraph('<font size=10>测试人员</font>',CNStyle))
component_data.append(thirdLine)
fourthLine.append(Paragraph('<font size=10>%s</font>'%(distance),CNStyle))
fourthLine.append(Paragraph('<font size=10>%s</font>'%(lidarIntensity),CNStyle))
fourthLine.append(Paragraph('<font size=10>%s</font>'%(temperature),CNStyle))
fourthLine.append(Paragraph('<font size=10>%s</font>'%(testPeople),CNStyle))
component_data.append(fourthLine)
component_table = Table(component_data, colWidths=90)
component_table.setStyle(TableStyle([('FONTSIZE', (-1, -1), (-2, -2), 10),
('LINEBEFORE', (0, 0), (0, -1), 0.1, colors.grey),
('GRID', (0, 0), (-1, -1), 0.5, colors.black)]))
story.append(component_table)
story.append(Spacer(1, 30))
def setBasicTestInfomation(basicInfomationList):
global LidarId
global LidarName
global testPeople
global distance
global lidarIntensity
global temperature
# if (len(fileNameList) != 6):
# return -1
LidarId = basicInfomationList[0]
LidarName = basicInfomationList[1]
testPeople = basicInfomationList[2]
distance = basicInfomationList[3]
lidarIntensity = basicInfomationList[4]
temperature = basicInfomationList[5]
return 0
def setFileName(fileNameList):
global pdfTitle_name
global DBfile_name
global outputfile_name
if (len(fileNameList) != 3):
return -1
pdfTitle_name = fileNameList[0]
DBfile_name = fileNameList[1]
outputfile_name = fileNameList[2]
return 0
def setPDFName(name):
doc = SimpleDocTemplate(name)
doc.build(story,onFirstPage=addExtraInfo, onLaterPages=addExtraInfo)
def setParam(laser):
global laserNum
laserNum = laser
return 0
def start():
global pdfTitle_name
global DBfile_name
global outputfile_name
pdfTitle(pdfTitle_name)
pdfBasicInfomation()
WaveReportchart(DBfile_name,"wave_distance","测远报告")
setPDFName(outputfile_name)
'''
# public interface
'''
if __name__ == '__main__':
argc = len(sys.argv)
laserNum = int(sys.argv[1])
print laserNum
fileNameList=[]
fileNameList.append(sys.argv[2])
print sys.argv[2]
fileNameList.append(sys.argv[3])
print sys.argv[3]
fileNameList.append(sys.argv[4])
print sys.argv[4]
basicInfoList = []
basicInfoList.append(sys.argv[5])
print sys.argv[5]
basicInfoList.append(sys.argv[6])
print sys.argv[6]
basicInfoList.append(sys.argv[7])
print sys.argv[7]
basicInfoList.append(sys.argv[8])
print sys.argv[8]
basicInfoList.append(sys.argv[9])
print sys.argv[9]
basicInfoList.append(sys.argv[10])
print sys.argv[10]
# laserNum = 40
# fileNameList = ['a','Avgwaveanalyse.db','aaaa']
# basicInfoList = ['0','40p','Yulin','100','500','20.0']
setFileName(fileNameList)
setBasicTestInfomation(basicInfoList)
setParam(laserNum)
start()