我正在努力如何使用另一种PDF作为模板在Python中创建PDF报告。 我有一个PDF文件(Template.pdf),可以用作模板每天创建报告。 Template.pdf如下所示:
ABC Corp
Daily Sales Report Report Date:
SalesName OrderQty ConfirmedQty ShippedQty
我需要以编程方式填写ReportDate和销售数据,并以PDF格式准备报告,如下所示: ABC公司
Daily Sales Report Report Date: 20120117
SalesName OrderQty ConfirmedQty ShippedQty
Jason 1000 900 50
Murali 2000 1000 900
可以假设没有。销售人员是固定的(即报告中没有固定行数。)
答案 0 :(得分:2)
您可以尝试使用reportlab,因为您的pdf模板相对容易。我不确定你将从哪里提取数据以及你的模板究竟是什么样子,但我写了一个小代码让你看到或开始。如果你能通过reportlab的用户指南,那就更好了。
你可以查看html到pdf的python解决方案。它应该是你正在寻找的东西。
Reportlab示例:
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.pagesizes import A4, letter, inch, cm
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle, Spacer, KeepTogether, CondPageBreak
from reportlab.lib import colors
from reportlab.lib.enums import TA_JUSTIFY, TA_LEFT, TA_CENTER
styles = getSampleStyleSheet()
class Sales( object ):
def __init__(self):
self.salesname = 'Jason'
self.orderqty = 1000
self.confirmqty = 900
self.shipqty = 50
jason = Sales()
# get current date
date = datetime.date.today()
jahr = date.year
monat = date.month
tag = date.day
story = []
# Styles
styleN = styles["BodyText"]
styleN.alignment = TA_LEFT
styleBH = styles["Normal"]
styleBH.alignment = TA_CENTER
styleH = styles["Heading2"]
# Static texts
title = "ABC Corp"
subtitle = "Daily Sales Report"
# Headers
hdescrpcion = Paragraph('''<b>SalesName</b>''', styleBH)
hpartida = Paragraph('''<b>OrderQty</b>''', styleBH)
hcandidad = Paragraph('''<b>ConfirmedQty</b>''', styleBH)
hprecio_unitario = Paragraph('''<b>ShippedQty</b>''', styleBH)
# Date
mydate = Paragraph('''Report Date: '''+str(jahr)+'''-'''+str(monat)+'''-'''+str(tag), styleN)
# 2 col data
data_2col =[[subtitle,mydate]]
table2 = Table(data_2col, colWidths=[5.05 * cm, 5* cm])
# 4 col data
data= [[hdescrpcion, hpartida,hcandidad, hprecio_unitario],
[jason.salesname, jason.orderqty, jason.confirmqty, jason.shipqty]]
table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 5 * cm,
3* cm])
table.setStyle(TableStyle([
('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
('BOX', (0,0), (-1,-1), 0.25, colors.black),
]))
story.append(Paragraph(title,styleH))
story.append(Spacer(1, 12))
story.append(table2)
story.append(Spacer(1, 12))
story.append(table)
doc = SimpleDocTemplate('template.pdf',pagesize = A4,rightMargin=18,leftMargin=18,
topMargin=18,bottomMargin=18, showBoundary=False, allowSplitting = True)
doc.build(story)