django 生成动态的PDF文件

Posted skbarcode

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于django 生成动态的PDF文件的主要内容,如果未能解决你的问题,请参考以下文章

Django - 使用 XHTML2PDF 创建和存储 PDF 文件

如何将动态生成的pdf文件添加到zipfile Python?

Django/Python:使用正确的语言生成 pdf

html模板到带有图像的pdf

PHP脚本,用于动态生成当前目录中存在的PDF文件的链接

在django中创建下载链接文件