导出pdf文件

时间:2019-09-19 17:42:51

标签: django

请帮助我,我只想导出pdf文件,我被卡在qs变量中,我不知道如何键入我搜索过的内容,但找不到完整答案。

views.py

 import io
 from django.http import FileResponse
 from reportlab.pdfgen import canvas


def export_page(request):
    buffer = io.BytesIO()
    p = canvas.Canvas(buffer)
    qs = Add.objects.all[0]
    p.drawString(100, 100, qs)
    p.showPage()
    p.save()
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename='hello.pdf')

1 个答案:

答案 0 :(得分:0)

我创建了新的utils.py文件

using python 3
pip install --pre xhtml2pdf 


    from io import BytesIO
    from django.http import HttpResponse
    from django.template.loader import get_template

    from xhtml2pdf import pisa

    def render_to_pdf(template_src, context_dict={}):
        template = get_template(template_src)
        html  = template.render(context_dict)
        result = BytesIO()
        pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
        if not pdf.err:
            return HttpResponse(result.getvalue(), content_type='application/pdf')
        return None



**VIEWS.PY** 

    from .utils import render_to_pdf # FOR PDF EXPORT
    from django.template.loader import get_template #FOR PDF EXPORT


    def pdf_view(request, *args, **kwargs):   #FOR PDF EXPORT
        template = get_template('invoice.html')
        qs = Add.objects.all()
        context = {'qs':qs}
        html  = template.render(context)
        pdf  = render_to_pdf('invoice.html', context)
        if pdf:
            return HttpResponse(pdf, content_type='application/pdf') # TILL HERE HTML TO PDF 
        return HttpResponse("Not found")

html页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>PDF EXPORT </title>
  <body>

        {% for i in qs %}   
        <div class='details'>
            budget:{{ i.budget }}<br/>
            expense: {{ i.expense }} <br/>
            Date:{{ i.date }}<br/>
            Name: {{i.business}}
            <hr class='hrItem' />
        </div>
        {% endfor %}


    </div>
    </body>
</html>