【问题标题】:Django generate pdf from a template with xhtml2pdfDjango 使用 xhtml2pdf 从模板生成 pdf
【发布时间】:2020-03-23 12:16:26
【问题描述】:

我尝试从我的 django 应用程序中的 html 模板生成 pdf 文件。

首先我安装库:

pip install --pre xhtml2pdf 

然后我在我的项目文件夹中创建一个具有此功能的 utils.py 文件:

from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template

from xhtml2pdf import pisa

def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html  = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None

我创建了我的 html 模板,然后在我的 views.py 文件中创建了类:

from yourproject.utils import render_to_pdf #created in step 4

class GeneratePdf(View):
    def get(self, request, *args, **kwargs):
        data = {
            'today': datetime.date.today(), 
            'amount': 39.99,
            'customer_name': 'Cooper Mann',
            'order_id': 1233434,
        }
        pdf = render_to_pdf('pdf/invoice.html', data)
        return HttpResponse(pdf, content_type='application/pdf')

此时在我的 urls.py 中添加开始 pdf 创建的 url

from idocuments.views import GeneratePdf
...

url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf),

但是当我启动我的应用程序并打开链接时出现错误:

init() 接受 1 个位置参数,但给出了 2 个

我认为问题出在我的 urls.py 中,但有人可以帮助我了解如何调用该函数以从 url 生成 pdf?

提前非常感谢

【问题讨论】:

标签: python django python-3.x xhtml2pdf


【解决方案1】:

在类名后使用 as_view()。

url(r'^fatt_doc/(?P<fat_num>\w+)/$', GeneratePdf.as_view()),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-15
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2017-05-07
    • 2019-04-11
    相关资源
    最近更新 更多