Python:将PDF转换为DOC

24

如何将pdf文件转换为docx。是否有使用Python进行此操作的方法?

我看到过一些允许用户上传PDF文件并返回DOC文件的页面,比如PdfToWord

提前感谢


我觉得你没有理解我的问题,我会编辑它。 - AlvaroAV
如果PDF数据是表格形式的,您可以使用tabula库来处理数据并输出为doc文档。 - Stuti Verma
7个回答

20
如果您已经安装了LibreOffice
lowriter --invisible --convert-to doc '/your/file.pdf'

如果您想使用Python来实现这个功能:
import os
import subprocess

for top, dirs, files in os.walk('/my/pdf/folder'):
    for filename in files:
        if filename.endswith('.pdf'):
            abspath = os.path.join(top, filename)
            subprocess.call('lowriter --invisible --convert-to doc "{}"'
                            .format(abspath), shell=True)

当我在终端上执行此命令时,它只会打开一个新的空白LibreOffice。我正在执行 lowriter --invisible --convert-to doc 'mypdf.pdf'。但这似乎是我要找的!谢谢! - AlvaroAV
@Liarez 你可以在参数中指定输出文件夹。默认情况下,转换后的文件可能会出现在~/Home目录中。请查看帮助选项(lowriter --help)。很抱歉,我现在无法测试它。 - user3058846
解决了!我终于成功让这个命令运行起来了!它按照预期工作,非常感谢你!! - AlvaroAV
6
请分享您使用LibreOffice将PDF转换为Word的命令。我已经安装了最新版本的LibreOffice。 - Steeve
2
对于 macOS 用户:/Applications/LibreOffice.app/Contents/MacOS/soffice --invisible --infilter="writer_pdf_import" --convert-to docx:"MS Word 2007 XML" file-to-convert.pdf - Leland

9
这很困难,因为PDF是以演示为导向的,而Word文档是以内容为导向的。我测试了两者,并推荐以下项目:
  1. PyPDF2
  2. PDFMiner
然而,在转换过程中,您肯定会失去演示方面的一些元素。

7
如果您想将PDF转换为类似docx的MS Word类型文件,我发现这个

Ahsin Shabbir写道:

import glob
import win32com.client
import os

word = win32com.client.Dispatch("Word.Application")
word.visible = 0

pdfs_path = "" # folder where the .pdf files are stored
for i, doc in enumerate(glob.iglob(pdfs_path+"*.pdf")):
    print(doc)
    filename = doc.split('\\')[-1]
    in_file = os.path.abspath(doc)
    print(in_file)
    wb = word.Documents.Open(in_file)
    out_file = os.path.abspath(reqs_path +filename[0:-4]+ ".docx".format(i))
    print("outfile\n",out_file)
    wb.SaveAs2(out_file, FileFormat=16) # file format for docx
    print("success...")
    wb.Close()

word.Quit()

这对我来说非常有效,转换了包含格式和图片的500页PDF文档。


2
我认为设置 word.visible = 1 是更好的选择。这将允许用户看到 Word 显示的所有消息或警告。如果我们设置 word.visible = 0,Word 将无法显示任何错误/警告,从而使调试体验变得更加复杂。 - raman
2
@eleks007先生,reqs_path未定义。 - Thuấn Đào Minh

2
您可以使用 GroupDocs.Conversion Cloud SDK for python 进行操作,无需安装任何第三方工具或软件。
示例 Python 代码:
# Import module
import groupdocs_conversion_cloud

# Get your app_sid and app_key at https://dashboard.groupdocs.cloud (free registration is required).
app_sid = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"
app_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Create instance of the API
convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key)
file_api = groupdocs_conversion_cloud.FileApi.from_keys(app_sid, app_key)

try:

        #upload soruce file to storage
        filename = 'Sample.pdf'
        remote_name = 'Sample.pdf'
        output_name= 'sample.docx'
        strformat='docx'

        request_upload = groupdocs_conversion_cloud.UploadFileRequest(remote_name,filename)
        response_upload = file_api.upload_file(request_upload)
        #Convert PDF to Word document
        settings = groupdocs_conversion_cloud.ConvertSettings()
        settings.file_path =remote_name
        settings.format = strformat
        settings.output_path = output_name

        loadOptions = groupdocs_conversion_cloud.PdfLoadOptions()
        loadOptions.hide_pdf_annotations = True
        loadOptions.remove_embedded_files = False
        loadOptions.flatten_all_fields = True

        settings.load_options = loadOptions

        convertOptions = groupdocs_conversion_cloud.DocxConvertOptions()
        convertOptions.from_page = 1
        convertOptions.pages_count = 1

        settings.convert_options = convertOptions
 .               
        request = groupdocs_conversion_cloud.ConvertDocumentRequest(settings)
        response = convert_api.convert_document(request)

        print("Document converted successfully: " + str(response))
except groupdocs_conversion_cloud.ApiException as e:
        print("Exception when calling get_supported_conversion_types: {0}".format(e.message))

我是Aspose的开发者宣传专员。


8
好主意,让我们向第三方发送可能涉密的文件。/s - Paradoxis
客户完全掌控他的云存储,并且可以使用任何他选择的云存储,例如Amazon S3/Google Drive/Azure存储/Dropbox/FTP存储等。 - Tilal Ahmad

1

根据之前的答案,这是我在使用Python 3.7.1时最有效的解决方案。

import win32com.client
import os

# INPUT/OUTPUT PATH
pdf_path = r"""C:\path2pdf.pdf"""
output_path = r"""C:\output_folder"""

word = win32com.client.Dispatch("Word.Application")
word.visible = 0  # CHANGE TO 1 IF YOU WANT TO SEE WORD APPLICATION RUNNING AND ALL MESSAGES OR WARNINGS SHOWN BY WORD

# GET FILE NAME AND NORMALIZED PATH
filename = pdf_path.split('\\')[-1]
in_file = os.path.abspath(pdf_path)

# CONVERT PDF TO DOCX AND SAVE IT ON THE OUTPUT PATH WITH THE SAME INPUT FILE NAME
wb = word.Documents.Open(in_file)
out_file = os.path.abspath(output_path + '\\' + filename[0:-4] + ".docx")
wb.SaveAs2(out_file, FileFormat=16)
wb.Close()
word.Quit()

0

在您的计算机上使用Adobe

如果您的计算机上安装了Adobe Acrobat,您可以使用以下功能将PDF文件保存为docx文件。

# Open PDF file, use Acrobat Exchange to save file as .docx file.

import win32com.client, win32com.client.makepy, os, winerror, errno, re
from win32com.client.dynamic import ERRORS_BAD_CONTEXT

def PDF_to_Word(input_file, output_file):
    
    ERRORS_BAD_CONTEXT.append(winerror.E_NOTIMPL)
    src = os.path.abspath(input_file)
    
    # Lunch adobe
    win32com.client.makepy.GenerateFromTypeLibSpec('Acrobat')
    adobe = win32com.client.DispatchEx('AcroExch.App')
    avDoc = win32com.client.DispatchEx('AcroExch.AVDoc')
    # Open file
    avDoc.Open(src, src)
    pdDoc = avDoc.GetPDDoc()
    jObject = pdDoc.GetJSObject()
    # Save as word document
    jObject.SaveAs(output_file, "com.adobe.acrobat.docx")
    avDoc.Close(-1)

请注意,输入文件和输出文件需要按照以下方式命名:
  1. D:\OneDrive...\file.pdf
  2. D:\OneDrive...\dafad.docx

这是否保留了所有格式,并且在Linux上能正常工作? - mike01010

0

对于安装了LibreOffice的Linux用户,请尝试

soffice --invisible --convert-to doc file_name.pdf

如果你遇到了像 Error: no export filter found, abording 这样的错误,请尝试以下方法。
soffice --infilter="writer_pdf_import" --convert-to doc file_name.pdf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接