首页 > 解决方案 > Django - 将 Canvas 对象作为 PDF 文件保存到 FileField

问题描述

(如何)在 FileField 中将画布对象另存为 PDF 文件是否可行?

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

视图.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)

Traceback:(要长粘贴所有)

[...]

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

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

标签: djangodjango-formsreportlab

解决方案


这并不理想,但是可以将文件(临时)写入磁盘,然后将其保存在 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)

推荐阅读