【问题标题】:How to get the rendered template from django?-pdfkit如何从 django 获取渲染的模板?-pdfkit
【发布时间】:2018-10-05 03:26:16
【问题描述】:

我的 django 应用程序中有一个模板,我需要将它呈现在一个变量中或将它保存在一个 html 文件中。

我的目标是将模板的 html 渲染转换为 pdf,我正在使用 pdfkit,因为它是我见过的最好的 html 到 pdf 转换器,reportlab 没有做我想要的。

当我尝试做这样的事情时:

pdf = pdfkit.from_file ('app / templates / app / table.html', 'table.pdf')

我得到了 pdf,但打印的是这样的:

enter image description here

感谢您的帮助!

【问题讨论】:

    标签: django-templates pdfkit


    【解决方案1】:

    这是我使用 django 2.0.1 和 pdfkit 0.6.1 的解决方案:

    获取模板:

    template = get_template ('plapp / person_list.html')
    

    用数据渲染它:

    html = template.render ({'persons': persons})
    

    继续views.py中方法的定义,直接在浏览器中下载pdf的方法:

    def pdf(request):
        persons = Person.objects.all()
        template = get_template('plapp/person_list.html')
        html = template.render({'persons': persons})
        options = {
            'page-size': 'Letter',
            'encoding': "UTF-8",
        }
        pdf = pdfkit.from_string(html, False, options)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment;
        filename="pperson_list_pdf.pdf"'
        return response    
    

    【讨论】:

    • 这是正确的答案仅当您的模板中没有指向图片的链接。否则,请勿使用此方法。仅当您执行 pdfkit.from_file 时,图像才会加载到 PDF 中。
    • response['Content-Disposition'] = 'attachment; filename="pperson_list_pdf.pdf"' 应该在一行中。
    【解决方案2】:
    from django.template.loader import get_template, render_to_string
    

    使用上述方法导入返回模板的函数。 get_template 返回模板对象,而 render_to_string 返回渲染模板的字符串。这是我使用 weasyprint 而不是 pdfkit 的方法。

    def weasy_pdf_generation(request, id):
        # my data
        _, _, draft_details = get_draft_details('setup', request, id)
        radios_dict = {k:v[1] for k,v in draft_details.items()}
        # rendering to string
        html_template = render_to_string('tax/setupreview report.html', radios_dict)
        styles = CSS(url="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
        pdf_file = HTML(string=html_template).write_pdf(stylesheets=[styles])
    
        #response details
        response = HttpResponse(pdf_file, content_type='application/pdf')
        response['Content-Disposition'] = 'filename="home_page.pdf"'
    return response
    

    【讨论】:

    • 感谢 machazthegamer!
    猜你喜欢
    • 2021-11-25
    • 2021-02-26
    • 2013-10-16
    • 2016-11-13
    • 2011-08-02
    • 2017-10-13
    • 2022-07-22
    • 2020-10-21
    • 2018-05-20
    相关资源
    最近更新 更多