【问题标题】:How can we convert uploaded docx file to pdf in django我们如何在 django 中将上传的 docx 文件转换为 pdf
【发布时间】:2020-07-15 11:32:20
【问题描述】:

我创建了一个接受文件的模型。我正在尝试将上传的 docx 文件转换为 pdf 并将其显示给用户。 为了将 docx 文件转换为 pdf,我正在尝试使用 python 的 docxtopdf 模块。 但是当我从request.FILES['Doc] 传递我的文件以转换函数时,它会给出错误:

TypeError at /convview/
expected str, bytes or os.PathLike object, not FieldFile

这里是views.py文件中的代码:

    def post(self, request, *args, **kwargs):
    form = self.get_form()
    if form.is_valid():
        pdffile=UserConvert(Doc=request.FILES['Doc'])
        pdffile.save()
        convert(pdffile.Doc)

当文件在内存中时,我们如何更改文件的 mime 类型?

【问题讨论】:

  • 这取决于托管 django 后端的服务器。 docx转PDF需要windows microsoft word或者linux上的libreoffice word
  • 我想知道我们如何将文件传递给 docxtopdf 转换函数进行转换,因为上面的错误是与文件字段相关的。
  • 请同时发布 'UserConvert()' 功能
  • UserConvert 是模型类:'class UserConvert(models.Model): Doc=models.FileField(upload_to='documents',blank=True )'
  • 对不起转换功能

标签: python django django-models file-conversion filefield


【解决方案1】:

您将 FieldFile 传递给函数,但需要一个 str、字节或路径:

TypeError expected str, bytes or os.PathLike object, not FieldFile

需要通过path参数获取文件的路径:

convert(pdffile.Doc.path)

【讨论】:

    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 2014-04-20
    • 2021-10-03
    • 2019-03-22
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多