我正在编写一个python脚本,它逐行解析一个csv文件,并使用jinja2创建一个HTML。理想情况下,每个单独的HTML实例(每一行一个)将被保存为PDF报告。
我已经做了很多搜索,而且我还没有找到一个很好的方法,从HTML到PDF使用python。是否可以将CGI呈现为PDF?你建议用什么方法来完成这个任务?
发布于 2017-04-19 21:07:38
如果您已经做了大量的搜索,那么我相信您已经看到了将html转换为pdf: ReportLab、weasyprint、pdfkit等的所有非常复杂的选项。
然而,我实际上只是花了最后一个月在Jinja2 -> HTML工作流上工作,所以希望我的解决方案能够帮助您。我发现下载wkhtmltopdf (一个用C编写的小型命令行程序--它非常棒),并从subprocess使用它是完成这项任务的最简单的方法。我的样本如下:
import os
import jinja2
import subprocess
def render(template_path, context):
# Context = jinja context dictionary
path, filename = os.path.split(template_path)
return jinja2.Environment(loader=jinja2.FileSystemLoader(path or './')
).get_template(filename
).render(context)
def create_pdf(custom_data, template_path, out_dir, context, keep_html=False):
# Custom data = the part of my workflow that won't matter to you
report_name = os.path.join(out_dir, custom_data + "_report")
html_name = report_name + ".html"
pdf_name = report_name + ".pdf"
def write_html():
with open(html_name, 'w') as f:
html = render(template_path, context)
f.write(html)
write_html()
args = '"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe" --zoom 0.75 -B 0 -L 0 -R 0 -T 0 {} {}'.format(html_name, pdf_name)
child = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
# Wait for the sub-process to terminate (communicate) then find out the
# status code
output, errors = child.communicate()
if child.returncode or errors:
# Change this to a log message
print "ERROR: PDF conversion failed. Subprocess exit status {}".format(
child.returncode)
if not keep_html:
# Try block only to avoid raising an error if you've already moved
# or deleted the html
try:
os.remove(html_name)
except OSError:
passjinja2和subprocess的文档很好地解释了这段代码的大部分内容,所以我不会在这里费力地浏览它。wkhtmltopdf中的arg标志转换为Zoom = 75%和0宽度边距( -B、-L等是底部、左侧等的缩写)。wkhtmltopdf文件也相当不错。
编辑:为render函数提供给马提亚斯·艾森。用法:
假设在/some/my_tpl.html上有一个模板,包含: 你好{{名字}} {姓氏}}!
context = {
'firstname': 'John',
'lastname': 'Doe'
}
result = render('/some/path/my_tpl.html', context)
print(result)你好,无名氏!
https://stackoverflow.com/questions/43505746
复制相似问题