在Python中从现有PDF创建新PDF

1 投票
1 回答
2317 浏览
提问于 2025-04-17 10:24

我正在努力学习如何在Python中使用另一个PDF作为模板来创建PDF报告。我有一个PDF文件(Template.pdf),可以用作每天生成报告的模板。Template.pdf的样子如下:

 ABC Corp

Daily Sales Report         Report Date:                                 

销售姓名 订单数量 确认数量 发货数量




我需要通过编程的方式填入报告日期和销售数据,并准备一个如下所示的PDF格式的报告:ABC公司


Daily Sales Report         Report Date: 20120117                        

销售姓名 订单数量 确认数量 发货数量


杰森 1000 900 50


彼得 500 50 450


穆拉利 2000 1000 900


可以假设销售人员的数量是固定的(也就是说,报告中的行数是固定的)。

1 个回答

2

你可以试试reportlab,因为你的PDF模板相对简单。我不太清楚你要从哪里获取数据,以及你的模板具体长什么样,但我写了一段小代码,帮你入门。最好还是看看reportlab的用户指南。

你也可以找找Python的HTML转PDF的解决方案,这个应该也符合你的需求。

下面是一个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)

撰写回答