如何通过python在ms word中打开pdf文件

0 人关注

我可以轻松地左键点击一个word文件,然后说用word打开。word自动将pdf充分转换为docx,没有格式化(我不需要格式化)。我想自动打开一批pdf文件,并把它们保存到另一个文件夹中,作为docx类型(最好是通过python)。有什么建议可以做到这一点吗?

我试过像pypdf2这样的python库,但它们不能得到文件的所有内容。 目前我不得不在ms word中手动打开pdf文件,然后保存它,再用python打开并处理它。

1 个评论
Alex
请分享你到目前为止的尝试。
python
pdf
ms-word
Tejas Paranjape
Tejas Paranjape
发布于 2020-08-05
1 个回答
Ruli
Ruli
发布于 2020-08-06
已采纳
0 人赞同

一个简单的解决方案是像这样使用os.system。

import os
os.system("'Path_to_your_word_exe' 'path_to_your_p df'")

在这个方案中,路径中的空格有问题,所以我建议使用子进程调用。

import subprocesss
subprocess.call([r'raw path to word', r'raw path to file'])
subprocess.call([r'C:\Program Files\Microsoft Office\root\Office16\WINWORD.exe', r'C:\Users\gopco\Downloads\SCYR.pdf'])

要对一个目录中的多个文件进行自动化作业,请使用以下代码。

import win32com.client
import os
#start word
word = win32com.client.Dispatch("Word.Application")
#allow word to print error messages (if any)
word.visible = 1
pdfs_path = "./" # folder with pdfs
reqs_path = "./" # folder for saving docx files
for i, doc in enumerate(glob.iglob(pdfs_path+"*.pdf")):
    filename = doc.split('\\')[-1] #get just the file name
    in_file = os.path.abspath(doc) #absolute path
    print(in_file)
    wb = word.Documents.Open(in_file) #open the pdf in word
    out_file = os.path.abspath(reqs_path +filename[0:-4]+ ".docx".format(i)) #set the filename for saving the docx
    print("outfile\n",out_file)
    wb.SaveAs2(out_file, FileFormat=16) # file format for docx