我带着一个我无法回答的新问题回来,整整一天都摸不着头脑。
我想通过点击"下载PDF"从网页生成PDF。按钮。我尝试了几个模块,包括Reportlab和XHTML2PDF,但我无法生成任何pdf,也无法下载...这是我在Reportlab上做的,Render HTML to PDF in Django site
- - views.py - -
import cStringIO as StringIO
import ho.pisa as pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def index_data(request):
#Code to generate data
return render(request, "analytics/stat.html", locals())
return render_to_pdf(
'analytics/stat.html',
{
'pagesize':'A4',
'mylist': results,
}
)
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))
- - urls.py - -
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', "analytics.views.main_page", name="main_page"),
url(r'^portail/$', "analytics.views.index_data", name="index"),
url(r'^generate_pdf/$', "analytics.views.GroupPDFGenerate.as_view()", name="generate_pdf")
- - 模板分析/ stat.html - -
{% extends "analytics/layout.html" %}
{% block title %}
Audience
{% endblock title %}
{% block head %}
# Script to generate google charts
{% endblock head %}
{% block body %}
<div class="page-header">
<h1 align="center"> Audience </h1>
</div>
<div class="row">
<div class="col-md-1">
<h3 align="center"><a href="/logout/">Logout</a></h3>
<h3 align="center"><a href="statistiques.pdf">Download pdf</a></h3>
</div>
</div>
{% endblock %}
此外,还有更好的模块可供处理吗?
答案 0 :(得分:7)
我建议使用wkhtmltopdf。
简短的回答?在Ubuntu上,安装二进制文件:
apt-get install wkhtmltopdf
在CentOS / RedHat上:
yum install wkhtmltox-0.12.2.1_linux-centos6-amd64.rpm
然后pip安装一个Python包:
pip install pdfkit
然后是代码:
import pdfkit
input_filename = 'README.html'
output_filename = 'README.pdf'
with open(input_filename, 'r') as f:
html_text = f.read()
pdfkit.from_string(html_text, output_filename)
对于长篇答案和细节,我整理了一篇博文:
http://www.peregrinesalon.com/blog/2015/06/python-3-django-generating-a-pdf-from-markdown-or-html/
这应该照顾PDF创作;你必须决定如何处理下载。祝你好运!
答案 1 :(得分:0)
如果您说您在生成PDF时遇到问题,我建议您先查看我在this answer中使用Reportlab,xhtml2pdf和django-easy-pdf中提到的示例。首先在浏览器中渲染PDF,然后继续获取下载链接。
答案 2 :(得分:-2)
from easy_pdf.rendering import render_to_pdf
def pdf(request):
with open('example.pdf', 'wb') as f2:
f2.write(render_to_pdf('you template', {'user': request.user}, encoding=u'utf-8'))