django 生成动态的PDF文件

 

 

需要依赖库.

WeasyPrint,它是一个Python库可以生成PDF文件从HTML模板中。
安装WeasyPrint

pip install WeasyPrint

创建一个PDF模板(template)
我们需要一个HTML文档给WeasyPrint输入。我们将要创建一个HTML
模板(template),渲染它使用Django,并且传递它给WeasyPrint来生成

PDF文件。

创建一个新的模板(template)文件在myapp应用的

templates目录下命名为pdf.html

<html>

    添加你要生成的页面

</html>

这个模板(template)就是PDF文件

渲染PDF文件
我们将要创建一个视图(view)来生成PDF文件。编辑myapp应用的views.py文件添加如下代码:

from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
import weasyprint
@staff_member_required
def admin_order_pdf(request, order_id):
    queryset = get_object_or_404(mymodel, id=mymodel_id)
    html = render_to_string('pdf.html',
    {'queryset': queryset})
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="mymodel_{}.pdf"'.format(mymodel.id)

    weasyprint.HTML(string=html).write_pdf(response,

        stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css'

    )])

    return response

接下来配置一个路由去访问就行了

 
分类: django
原文地址:https://www.cnblogs.com/skbarcode/p/12569277.html