lhd*_*d93 1 django-templates pdfkit
我的 django 应用程序中有一个模板,我需要将它呈现在一个变量中或将其保存在一个 html 文件中。
我的目标是将模板的 html 渲染转换为 pdf,我正在使用 pdfkit,因为它是我见过的最好的 html 到 pdf 转换器,reportlab 没有做我想要的。
当我尝试做这样的事情时:
pdf = pdfkit.from_file ('app / templates / app / table.html', 'table.pdf')
Run Code Online (Sandbox Code Playgroud)
我得到了 pdf,但打印出如下内容:
我感谢任何帮助!
这是我使用 django 2.0.1 和 pdfkit 0.6.1 的解决方案:
获取模板:
template = get_template ('plapp / person_list.html')
Run Code Online (Sandbox Code Playgroud)
用数据渲染它:
html = template.render ({'persons': persons})
Run Code Online (Sandbox Code Playgroud)
继续在views.py中定义方法,直接在浏览器中下载pdf:
def pdf(request):
persons = Person.objects.all()
template = get_template('plapp/person_list.html')
html = template.render({'persons': persons})
options = {
'page-size': 'Letter',
'encoding': "UTF-8",
}
pdf = pdfkit.from_string(html, False, options)
response = HttpResponse(pdf, content_type='application/pdf')
response['Content-Disposition'] = 'attachment;
filename="pperson_list_pdf.pdf"'
return response
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3379 次 |
| 最近记录: |