Python在修改文档后将DOCX转换为PDF并导出PDF下载(DJANGO)

Python在修改文档后将DOCX转换为PDF并导出PDF下载(DJANGO),python,django,Python,Django,我有一个Django应用程序,可以读取文档模板(DOCX)并对其进行修改。该程序运行良好,但正在返回下载DOCX文档(如预期的那样)。所以,我想编辑下载文件格式为PDF。我曾想过将DOCX文件转换成PDF,但我找不到一个可行的方法 我的实际代码如下所示: f = io.BytesIO() document.write(f) length = f.tell() f.seek(0) response = HttpResponse( f.get

我有一个Django应用程序,可以读取文档模板(DOCX)并对其进行修改。该程序运行良好,但正在返回下载DOCX文档(如预期的那样)。所以,我想编辑下载文件格式为PDF。我曾想过将DOCX文件转换成PDF,但我找不到一个可行的方法

我的实际代码如下所示:

    f = io.BytesIO()
    document.write(f)
    length = f.tell()
    f.seek(0)

    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )

    response['Content-Disposition'] = 'attachment; filename=' + formular.name + '.docx'
    response['Content-Length'] = length
    return response

我想找到一种工作方法,将DOCX文件f转换为PDF文件,然后再将其作为响应返回。

为此,您需要pywin32库。你可以这样用

   def convert_to_pdf(doc):
      try:
       word = client.DispatchEx("Word.Application")
      new_name = doc.replace(".docx", r".pdf")
      worddoc = word.Documents.Open(doc)
      worddoc.SaveAs(new_name, FileFormat = 17)
      worddoc.Close()
     except Exception, e:
        return e
     finally:
        word.Quit()

在python中将docx转换为pdf:应该提到的是,必须安装Word才能使其正常工作。