如何生成和打印文档(Python)

5 投票
1 回答
11128 浏览
提问于 2025-04-17 04:40

我需要让用户能够编辑和打印与客户相关的文件(比如发票等)。

用户填写打印表单(选择客户、月份,以及每种四种文件需要多少份),然后点击打印按钮。

接下来,我的系统应该执行以下步骤(算法):

result = create new word-friendly file  # because user may manually edit it later

for client in form_clients:

    snapshot = select row in snapshots table 
               where client == client and month == form_month

    document1 = generate_from_template(snapshot, tpl1.docx)
    for 1 to form_how_much_copies_of_1_type_of_document_he_or_she_needs:
        result += document1

    document2 = generate_from_template(snapshot, tpl2.docx)
    for 1 to form_how_much_copies_of_2_type_of_document_he_or_she_needs:
        result += document2

    document3 = generate_from_template(snapshot, tpl3.docx)
    for 1 to form_how_much_copies_of_3_type_of_document_he_or_she_needs:
        result += document3

    document4 = generate_from_template(snapshot, tpl4.docx)
    for 1 to form_how_much_copies_of_4_type_of_document_he_or_she_needs:
        result += document4

print result

需求:

  • 能够编辑结果(需要一个适合Word的格式)
  • 分页(每个文件都要在新的一页上)
  • 表格,不能太简单,看看发票模板的例子: tpl example
  • 字体大小和样式(比如加粗)
  • 保存文本位置

我的问题是如何生成这个文件(结果)?有一个https://github.com/mikemaccana/python-docx的项目,但我不确定它是否能和模板一起使用(或者至少能生成我需要的表格)……

或者我可以把所有的.docx模板保存为html,然后像普通的Django模板一样使用,但不确定如何把它们合并成一个文档并创建分页……

或者我应该看看其他兼容Word的文件格式?……

附注:最好使用Python,但这不是关键,我也可以使用Java、Perl、Ruby、PHP、Bash等,并安装任何新的Ubuntu兼容包……

1 个回答

5

如果你不一定要使用模板,或者愿意用代码重新创建模板,可以使用reportlab这个库来生成PDF文件,然后打印出来。

这里有一个关于如何制作表格的例子: http://www.blog.pythonlibrary.org/2010/09/21/reportlab-tables-creating-tables-in-pdfs-with-python/

另外,这里还有一个发票的例子: https://github.com/radzhome/fedex-commercial-invoice

撰写回答