django-rest-framework中的Pdf

sqougxex  于 2023-04-07  发布在  Go
关注(0)|答案(2)|浏览(139)

我正在尝试在Django中创建PDF

from xhtml2pdf import pisa
 from django.http import HttpResponse
 from django.template.loader import get_template
 from django.template import Context 
 from rest_framework.views import APIView
 from .models import Brand

 class ABCView(APIView):
   def post(self, request,format=None):
    report = Brand.objects.all()
    template_path = 'profile_brand_report.html'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

    context = {'report': report}
    template = get_template(template_path)
    html = template.render(Context(context))
    print (html)

    pisaStatus = pisa.CreatePDF(html, dest=response)

    return response

但我得到了一个意外的错误,我不知道我做错了什么,我得到了这个错误

argument of type 'Context' is not iterable

还是有其他方法可以做到这一点。提前感谢帮助

wwwo4jvm

wwwo4jvm1#

我们不需要使用一个基于类的视图。为了简单起见,我们可以使用一个基于函数的视图。修改你的代码如下。

from django.template.loader import render_to_string

def generate_pdf(request):
    report = Brand.objects.all()
    template_path = 'profile_brand_report.html'

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'

    html = render_to_string(template_path, {'report': report})
    print (html)

    pisaStatus = pisa.CreatePDF(html, dest=response)

    return response

我们也可以使用wkhtmltopdf在django中生成PDF。
阅读:https://learnbatta.com/blog/django-html-to-pdf-using-pdfkit-and-wkhtmltopdf-5/

yx2lnoni

yx2lnoni2#

我希望工作这个

def generate_pdf(data):
    buffer = BytesIO()
    p = canvas.Canvas(buffer, pagesize=letter)
    for row, item in enumerate(data):
        for col, value in enumerate(item.values()):
            p.drawString(col * 100 + 20, row * 30 + 20, str(value).encode('utf-8'))

    p.showPage()
    p.save()
    buffer.seek(0)
    pdf_output = buffer.getvalue()
    buffer.close()
    return pdf_output

相关问题