Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

python写一个将PDF转换成word的代码

  1. User

    python写一个将PDF转换成word的代码

  2. Assistant

    要将PDF转换为Word,可以使用Python的pytesseract库和python-docx库。

    首先,确保已经安装了pytesseract和python-docx库。可以使用以下命令安装这两个库:

    pip install pytesseract
    pip install python-docx
    

    然后,使用以下代码将PDF转换为Word:

    import pytesseract
    from PIL import Image
    from pdf2image import convert_from_path
    from docx import Document
      
    def pdf_to_word(pdf_path, output_path):
        pages = convert_from_path(pdf_path)
    
        document = Document()
    
        for idx, page in enumerate(pages):
            image_path = f"page{idx}.jpg"
            page.save(image_path, 'JPEG')
            text = pytesseract.image_to_string(Image.open(image_path))
            document.add_paragraph(text)
        
        document.save(output_path)
        print("转换成功!")
    
    # 测试例子
    pdf_path = "example.pdf"
    output_path = "example.docx"
    
    pdf_to_word(pdf_path, output_path)
    

    请确保将pdf_path替换为你要转换的PDF文件的路径,将output_path替换为你要保存的Word文件的路径。

    此代码首先将PDF的每一页转换为图像,然后使用pytesseract库将图像中的文本提取出来。最后,使用python-docx库将提取的文本保存为Word文件。