【发布时间】:2021-06-06 15:33:43
【问题描述】:
我想用我编写的一个 Python 小程序生成发票。我希望它首先将发票输出为 HTML 文件,然后将其转换为 PDF。目前我的代码正在根据需要创建 HTML 文档,但它正在输出一个空白 PDF 文件:
import pdfkit
import time
name = input('Enter business name: ')
date = input('Enter the date: ')
invoice = input('Enter invoice number: ')
total = 1000 # Fixed number for now just for testing purposes
f = open('invoice.html','w')
message = f"""<html>
<head>
<link rel='stylesheet' href='style.css')>
</head>
<body>
<h1>INVOICE<span id="invoice-number"> {invoice}</h1>
<h3>{date} </h3>
<h3>{name} </h3>
<h3>Total: ${total}</h3>
</body>
</html>"""
f.write(message)
time.sleep(2)
options = {
'enable-local-file-access': None
}
pdfkit.from_file('invoice.html', 'out.pdf', options = options)
当我运行上面的代码时,它输出的 HTML 文档看起来不错,但它创建的 PDF 是空白的。我根本没有收到任何错误消息。终端中的输出是:
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
但是,我在同一目录中有另一个名为 test.py 的文件。该文件包含导入语句,最后四行与第一行代码完全相同,仅此而已:
import pdfkit
options = {
'enable-local-file-access': None
}
pdfkit.from_file('invoice.html', 'out.pdf', options = options)
如果我在前一个文件之后运行此文件,它会正确输出 PDF,使其看起来像 HTML 版本。为什么这段代码在单独的文件中运行时有效,但在包含在原始文件中时无效?如何让它在同一个文件中运行,这样我就不必执行两个命令来获取发票?
【问题讨论】:
-
顺便说一句,当您创建minimal reproducible example 时,您应该修复所有输入。您对
total的想法是正确的。在这种情况下不是问题,但我看到了完全不可重现的代码,因为 OP 没有正确指定它们的输入。