django - 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'
如果需要更多信息,请告诉我!
解决方案
这并不理想,但是可以将文件(临时)写入磁盘,然后将其保存在 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)
推荐阅读
- python - 仅通过电子邮件地址使用 gmail api 访问用户个人资料信息
- asp.net - 在不同软件中使用 IdentityServer 登录后设置声明
- java - Java客户端C++服务器数据发送/接收问题
- python - Python 输入类型错误:'_io.TextIOWrapper' 对象不可调用
- android - 限制底部工作表向下滑动
- ruby-on-rails - 将 ActiveRecord 查询记录的字段从 1 更新为 n 而不循环
- python - 无法在我的串行控制台上读取 RFID 标签号
- azure - 如何使用 Mongodb shell 打开到 Cosmos DB 模拟器的经过身份验证的连接?
- apache-spark - Spark - 找不到异常 org.apache.spark.Logging
- javascript - React - 从父级到子级访问函数参数