将 Django 模板转换为 pdf

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

我的应用程序需要将报告邮寄给客户,因此我需要一种有效的方法将动态模板转换为 pdf 报告(包括通过 Chart.js 生成的图像)。我已经尝试过 pdfkit 但它需要一个 URL(它很可能在该 URL 上执行 GET,但模板在几次 AJAX 调用后会生成一个报告,因此 GET 将只返回带有一些过滤器的普通页面)并且它不包含图像(我猜我可以通过使用 dataToURL 将图表图像转换为 png 并保存在服务器上来解决)。

我在这里看到的唯一选项是保存动态生成的所有数据以及 html 标签,并在服务器上重新创建文件,然后转换为 pdf。我确信有更好的解决方案。如果这看起来很基础,我很抱歉,但我不是职业程序员。

javascript python django pdf
3个回答
5
投票

Django 有几个用于输出 PDF 的选项,其中最灵活的是 ReportLab

但是,要在传递上下文数据的同时将 Django 模板渲染为 PDF,Weasyprint/xhtml2pdf 非常简单。下面是使用早期 xhtml2pdf 库的视图示例。这是标准的 Django 视图。

需要明确的是,所有这些库都采用 Django 模板,渲染它并返回 PDF。存在局限性(例如,Pisa 只有少数可以渲染的 CSS 参数)。无论如何,看看这三个;至少有一个能完全满足您的需要。

from django_xhtml2pdf.utils import generate_pdf

def myview(request):
    resp = HttpResponse(content_type='application/pdf')
    dynamic_variable = request.user.some_special_something
    context = {'some_context_variable':dynamic_variable}
    result = generate_pdf('my_template.html', file_object=resp, context=context)
    return result

1
投票

您可以使用付费库,即 pdfcrowd,它将网页转换为 pdf。像这样..

首次安装-

pip install pdfcrowd

然后使用图书馆 -

import pdfcrowd
from django.http import HttpResponse

def generate_pdf_view(request):
    try:
        # create an API client instance
        client = pdfcrowd.Client("username", "apikey")

        # convert a web page and store the generated PDF to a variable
        pdf = client.convertURI("http://www.yourwebpage.com")

         # set HTTP response headers
        response = HttpResponse(mimetype="application/pdf")
        response["Cache-Control"] = "max-age=0"
        response["Accept-Ranges"] = "none"
        response["Content-Disposition"] = "attachment; filename=google_com.pdf"

        # send the generated PDF
        response.write(pdf)
    except pdfcrowd.Error, why:
        response = HttpResponse(mimetype="text/plain")
        response.write(why)
    return response

您可以通过此处注册获取用户名和 APIKEY - http://pdfcrowd.com/pricing/api/


0
投票

选项A:抓取

您可以使用PhantomJSCasperJS之类的东西来导航和抓取HTML页面。

选项B:一代

您可以使用PyPDF之类的东西,如此处建议

哪个选项更好?

抓取可以让您不必维护两个模板。使用 Generation,您可以通过以下事实获得更多控制:您是专门为 PDF 编写的,并且您隐式拥有两个模板。

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