zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    居中
    <script type="text/javascript"></script>
    移动端获取全文高度
    video
    transition animation
    移动端隐藏overflow:auto滚轮
    Vue将组件data内的数据重置
    文字刚刚刚刚刚好的居中
    小程序总结(不断更新)
    vue组件之间的传值
  • 原文地址:https://www.cnblogs.com/pythonClub/p/10433638.html
Copyright © 2011-2022 走看看