Django-将Canvas对象另存为PDF文件到FileField

时间:2018-07-02 15:46:19

标签: django django-forms reportlab

(如何)可以将画布对象另存为FileField中的PDF文件?

https://docs.djangoproject.com/en/2.0/howto/outputting-pdf/#outputting-pdfs-with-django

views.py

from django.views.generic.edit import FormView
from reportlab.pdfgen import canvas

class SomeView(FormView):

    form_class = SomeForm
    template_name = 'sometemplate.html'


    def form_valid(self, form):

        item = form.save(commit=False)

        # create PDF
        filename = "somefile.pdf"
        p = canvas.Canvas(filename)
        p.drawString(100, 100, "Hello world.")
        p.showPage()
        p.save()

        # this will not work, but i hope there is another way
        # Error: 'Canvas' object has no attribute '_committed'
        item.file = p

        # save form
        item.save()

        return super(SomeView, self).form_valid(form)

跟踪:(要长时间粘贴所有内容)

[...]

Exception Type: AttributeError at /return/
Exception Value: 'Canvas' object has no attribute '_committed'

如果需要更多信息,请告诉我!

2 个答案:

答案 0 :(得分:0)

尝试:

def some_view(request):
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    p = canvas.Canvas(response)
    p.drawString(100, 100, "Hello world.")
    p.showPage()
    p.save()

    return response

答案 1 :(得分:0)

这不是理想的方法,但是它可以将文件(临时文件)写入磁盘,然后将其保存在FileField中(此后需要删除临时文件,该文件不在代码中)

from reportlab.pdfgen import canvas
from django.core.files import File
import codecs

class SomeView(FormView):

    form_class = SomeForm
    template_name = 'sometemplate.html'


    def form_valid(self, form):

        item = form.save(commit=False)

        # create PDF
        filename = "somefile.pdf"
        p = canvas.Canvas(filename)
        p.drawString(100, 100, "Hello world.")
        p.showPage()
        p.save()

        with codecs.open('somefile.pdf', "r",encoding='utf-8', errors='ignore') as f:   
           item.file.save('somefile.pdf',File(f))

        # save form
        item.save()

        return super(SomeView, self).form_valid(form)