如何将Reportlab与基于Django Class的View相结合?

问题描述 投票:0回答:1

我正在尝试将HTML转换为PDF。我看了这个教程,https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/和我能够成功地使用硬编码值的教程。问题是......我无法弄清楚如何动态地将我的模型和它的属性合并到这个例子中。

以下是我遵循的步骤......

首先,我使用以下版本将reportlab安装到我的环境中...

pip install --pre xhtml2pdf 

这有效......

然后我按照指示将utils.py文件添加到我的项目中。

然后我将此代码复制到我的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文件,如下所示:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Title</title>
        <style type="text/css">
            body {
                font-weight: 200;
                font-size: 14px;
            }
            .header {
                font-size: 20px;
                font-weight: 100;
                text-align: center;
                color: #007cae;
            }
            .title {
                font-size: 22px;
                font-weight: 100;
               /* text-align: right;*/
               padding: 10px 20px 0px 20px;  
            }
            .title span {
                color: #007cae;
            }
            .details {
                padding: 10px 20px 0px 20px;
                text-align: left !important;
                /*margin-left: 40%;*/
            }
            .hrItem {
                border: none;
                height: 1px;
                /* Set the hr color */
                color: #333; /* old IE */
                background-color: #fff; /* Modern Browsers */
            }
        </style>
    </head>
    <body>
        <div class='wrapper'>
            <div class='header'>
                <p class='title'>Invoice # </p>
            </div>
        <div>
        <div class='details'>
            Bill to: {{ customer_name }} <br/>
            Amount: {{ amount }} <br/>
            Date: 
            <hr class='hrItem' />
        </div>
    </div>
    </body>
</html>

我还创建了必要的URL ....

然后我创建了一个类似于下面定义的视图:

from django.http import HttpResponse
from django.views.generic import View

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')

当我点击我的链接到这个视图...输出显示就像教程说的那样......

但是,如果我想让我的模型以这种格式显示......我很难过如何做到这一点。我尝试了一个DetailView ....然后我得到了数据,但没有PDF ....我也搜索了很多其他地方,我似乎无法找到一个允许我动态获取模型的示例在属性中根据需要...提前感谢任何帮助或指针。

django django-models django-templates django-views reportlab
1个回答
3
投票

如果你想使用DetailView,我想你可以这样做:

class SomeDetailView(DetailView):
    model = YourModel
    template_name = 'pdf/invoice.html'

    def get_context_data(self, **kwargs):
        context = super(SomeDetailView, self).get_context_data(**kwargs)
        # add extra context if needed
        return context

    def render_to_response(self, context, **kwargs):
        pdf = render_to_pdf(self.template_name, context)
        return HttpResponse(pdf, content_type='application/pdf')

在这里,我将覆盖render_to_response以覆盖DetailView的默认响应以返回PDF响应。在这里,来自get_context_data的背景。在get_context_data中,您可以根据需要添加任何额外的上下文。

© www.soinside.com 2019 - 2024. All rights reserved.