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



(如何(是否可以将画布对象另存为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'

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

尝试:

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

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

最新更新