要将word文件转换成pdf文件,可以使用Python的pywin32库结合Microsoft Office软件来实现。
方法一:

import win32com.client as win32def word_to_pdf(input_file, output_file):word = win32.gencache.EnsureDispatch('Word.Application')doc = word.Documents.Open(input_file)doc.SaveAs(output_file, FileFormat=17)doc.Close()word.Quit()# 示例使用input_file = 'input.docx'output_file = 'output.pdf'word_to_pdf(input_file, output_file)

在代码中,首先导入了win32com.client模块,并使用EnsureDispatch方法来创建一个Word应用程序的对象。然后使用Documents.Open方法打开输入的Word文件。

通过调用SaveAs方法,并将FileFormat参数设置为17,可以将Word文件保存为PDF格式。最后,使用Close方法关闭打开的文档,并使用Quit方法关闭Word应用程序。

请注意,此代码需要安装pywin32库和Microsoft Office软件才能正常运行。

方法二:
此方法适用于linux和Windows环境,方法一只适用于Windows环境

# word转Pdfdef word_change_pdf(word_file_path):"""将word文件转换成pdf文件:param word_file_path: word文件地址:return: 返回转成的pdf地址信息"""suffix = os.path.basename(word_file_path).split('.')[1]# 另存为pdf文件pdf_path = word_file_path.replace(suffix, "pdf")out_dir = pdf_path.rsplit('/', 1)[0] + '/'if 'window' in os_system:# LibreOffice本地位置D:/Download/LibreOffice/program/soffice.execommand = ['D:/Download/LibreOffice/program/soffice.exe', '--convert-to', 'pdf', '--outdir', out_dir, word_file_path]else:# LibreOffice在虚拟机的位置:/usr/bin/libreoffice7.6command = ['/opt/libreoffice7.6/program/soffice.bin', '--convert-to', 'pdf', '--outdir', out_dir, word_file_path]subprocess.Popen(command).communicate()return pdf_path