将Django模板转换为pdf格式

Convert Django template to pdf

本文关键字:pdf 格式 转换 Django      更新时间:2023-09-26

我的应用程序需要向客户邮寄报告,因此我需要一种有效的方法将动态模板转换为PDF报告(包括通过chart.js生成的图像)。我尝试过pdfkit,但它需要一个URL(它最有可能执行GET,但然后模板生成几个AJAX调用后的报告,所以GET将只是返回一些过滤器的普通页面),它不包括图像(我猜我可以通过使用dataToURL将图表图像转换为png并保存在服务器上)。

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

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

您可以使用付费库,即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/

选项A:抓取

你可以使用像PhantomJS或CasperJS之类的东西来导航和抓取HTML页面。

选项B: Generation

您可以使用此处建议的PyPDF之类的文件。

哪个选项更好?

抓取使您不必维护两个模板。使用Generation,您可以获得更多的控制,因为您是专门为PDF编写的,并且您隐式地有两个模板。