在Django网站中将HTML渲染为PDF

131 投票
10 回答
138857 浏览
提问于 2025-04-15 14:04

我在用Django搭建网站,现在想找个简单的方法把动态的HTML页面转换成PDF文件。

这些页面里有HTML内容,还有用谷歌可视化API生成的图表(这个是基于JavaScript的,但这些图表是必须包含的)。

10 个回答

12

https://github.com/nigma/django-easy-pdf

模板:

{% extends "easy_pdf/base.html" %}

{% block content %}
    <div id="content">
        <h1>Hi there!</h1>
    </div>
{% endblock %}

视图:

from easy_pdf.views import PDFTemplateView

class HelloPDFView(PDFTemplateView):
    template_name = "hello.html"

如果你想在Python 3上使用django-easy-pdf,可以查看这里推荐的解决方案 这里

15

试试 wkhtmltopdf,可以配合以下其中一个工具使用

django-wkhtmltopdf 或者 python-pdfkit

这个对我来说效果很好,支持JavaScript和CSS,基本上任何网页浏览器能支持的东西它都能处理。

想要更详细的教程,可以看看这篇 博客文章

227

试试来自 Reportlab 的解决方案。

下载它,然后像往常一样用 python setup.py install 来安装。

你还需要用 easy_install 安装以下模块:xhtml2pdf、html5lib 和 pypdf。

这里有一个使用示例:

首先定义这个函数:

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>

撰写回答