gpt4 book ai didi

python - 在 Django 站点中将 HTML 渲染为 PDF

转载 作者:IT老高 更新时间:2023-10-28 21:06:14 25 4
gpt4 key购买 nike

对于我的 django 网站,我正在寻找一种将动态 html 页面转换为 pdf 的简单解决方案。

页面包含来自 Google 可视化 API 的 HTML 和图表(基于 javascript,但必须包含这些图表)。

最佳答案

尝试 Reportlab 中的解决方案.

下载它并像往常一样使用 python setup.py install 安装它

您还需要安装以下模块:xhtml2pdf、html5lib、pypdf with easy_install。

这是一个用法示例:

先定义这个函数:

import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape


def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

那么你可以这样使用它:

def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)

模板:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>

希望对你有帮助。

关于python - 在 Django 站点中将 HTML 渲染为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1377446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com