先讲一下为啥要写这个文章,网上其实很多这种pdf转化的代码和软件。我一直想用python做,但是网上搜到的代码很多都不能用,很多是2.7版本的代码,再就是pdf需要用到的库在导入的时候,很多的报错,解决起来特别费劲,而且自从2021年初以来,似乎网上很少有关pdf转化的代码出现了。我在研究了很多代码和pdfminer的用法后,总结了几个方法,目前这几种方法可以解决大多数格式的转化,后面我也专门放了提取pdf表格的代码,文末有高效的免费在线工具推荐。

下面这个是我最最推荐的方法 ,简单高效 ,只要是标准pdf文档,里面的图片和表格都可以保留格式

# pip install pdf2docx #安装依赖库
from pdf2docx import converter

pdf_file = r'c:\users\administrator\desktop\新建文件夹\mednine.pdf'
docx_file = r'c:\users\administrator\desktop\python教程.docx'

# convert pdf to docx
cv = converter(pdf_file)
cv.convert(docx_file, start=0, end=none)
cv.close()

下面是另外三种常用方法

1 把标准格式的pdf转为word,测试环境python3.6.5和3.6.6(注意pdf内容仅仅是文字为主的里面没有图片图表的适用,不适合扫描版pdf,因为那只能用图片识别的方式进行)

from pdfminer.pdfinterp import pdfresourcemanager, pdfpageinterpreter
from pdfminer.converter import textconverter
from pdfminer.layout import laparams
from pdfminer.pdfpage import pdfpage
from io import stringio
import sys
import string
from docx import document


def convert_pdf_2_text(path):
    rsrcmgr = pdfresourcemanager()
    retstr = stringio()
    
    device = textconverter(rsrcmgr, retstr, codec='utf-8', laparams=laparams())
    interpreter = pdfpageinterpreter(rsrcmgr, device)
    
    with open(path, 'rb') as fp:
        for page in pdfpage.get_pages(fp, set()):
            interpreter.process_page(page)
            #print(retstr.getvalue())  
        text = retstr.getvalue()
    device.close()
    retstr.close()
    return text


def pdf2txt():
    text=convert_pdf_2_text(path)
    with open('real.txt','a',encoding='utf-8') as f:
        for line in text.split('\n'):
            f.write(line+'\n')

        

def remove_control_characters(content):
    mpa = dict.fromkeys(range(32))
    return content.translate(mpa)
    
def save_text_to_word(content, file_path):     

    doc = document()
    for line in content.split(''):
        print(line)
            
        paragraph = doc.add_paragraph()
        paragraph.add_run(remove_control_characters(line))
    doc.save(file_path)


if __name__ == '__main__':
    path = r'c:\users\mayn\desktop\程序临时\培训教材.pdf'  # 你自己的pdf文件路径及文件名 不适合扫描版 只适合标准pdf文件
    text = convert_pdf_2_text(path)
    save_text_to_word(text, 'output.doc')  #pdf转为word方法
    #pdf2txt()  #pdf转为txt方法

2专门提取pdf里面的表格,使用pdfplumber适合标准格式的pdf

import pdfplumber
import pandas as pd
import time
from time import  ctime
import psutil as ps 
#import threading
import gc
pdf = pdfplumber.open(r"c:\users\administrator\desktop\新建文件夹\mednine.pdf")
n=len(pdf.pages)
print('总共有',n,'页')

def pdf2exl(i): # 读取了第i页,第i页是有表格的,
    print('********************************************************************************************************************************************************')
    print('正在输出第',str(i+1),'页表格')
    print('********************************************************************************************************************************************************')   
    p0 = pdf.pages[i]
    try:
        table = p0.extract_table()
        print(table)
    
        df = pd.dataframe(table[1:], columns=table[0])
    #print(df)
        df.to_excel(r"c:\users\administrator\desktop\新建文件夹\model"+str(i+1)+".xlsx")
    
        #df.info(memory_usage='deep')
        
        
    except exception as e:
        print('第'+str(i+1)+'页无表格,或者检查是否存在表格')       
       
        pass
    #print('目前内存占用率是百分之',str(ps.virtual_memory().percent),'    第',str(i+1),'页输出完毕')
    print('**********************************************************************************************************************************************************')
    print('\n\n\n') 
    time.sleep(5)


def dojob1():  #此函数  直接循环提取pdf里面各个页面的表格 
    print('*********************')
    for i in range(0,n):
        pdf2exl(i)    

3也可以提取pdf里面的表格,使用camelot(camelot的安装可能需要点耐心,反正用的人不多)

import camelot
import wand

# 从pdf文件中提取表格

def output(i):  
    #print(tables)
    #for i in range(5):
    tables = camelot.read_pdf(r'c:\users\administrator\desktop\新建文件夹\mednine.pdf', pages=str(i), flavor='stream')
    print(tables[i])
    
# 表格数据
    print(tables[i].data)
    
    tables[i].to_csv(r'c:\users\administrator\desktop\新建文件夹
import camelot
import wand
# 从pdf文件中提取表格
def output(i):  
#print(tables)
#for i in range(5):
tables = camelot.read_pdf(r'c:\users\administrator\desktop\新建文件夹\mednine.pdf', pages=str(i), flavor='stream')
print(tables[i])
# 表格数据
print(tables[i].data)
tables[i].to_csv(r'c:\users\administrator\desktop\新建文件夹\002'+str(i)+r'.csv')
def plotpdf():
# 这个是画pdf 结构的函数 现在不能用 不要打开
#print(tables[0])
tables = camelot.read_pdf(r'c:\users\mayn\desktop\vcode工作区\11\路基.pdf', pages='200', flavor='stream')
camelot.plot(tables[0], kind='text')
print(tables[0])
plt.show()
# 绘制pdf文档的坐标,定位表格所在的位置  
#plt = camelot.plot(tables[0],kind='text')
#plt.show()
#table_df = tables[0].df
#plotpdf() 
#i=3
#output(i)
for i in range(0,2):
try:    
output(i)
except exception as e:
print('第'+str(i)+'页没找到表格啊啊啊')
pass 
continue
2'+str(i)+r'.csv') def plotpdf(): # 这个是画pdf 结构的函数 现在不能用 不要打开 #print(tables[0]) tables = camelot.read_pdf(r'c:\users\mayn\desktop\vcode工作区\路基.pdf', pages='200', flavor='stream') camelot.plot(tables[0], kind='text') print(tables[0]) plt.show() # 绘制pdf文档的坐标,定位表格所在的位置 #plt = camelot.plot(tables[0],kind='text') #plt.show() #table_df = tables[0].df #plotpdf() #i=3 #output(i) for i in range(0,2): try: output(i) except exception as e: print('第'+str(i)+'页没找到表格啊啊啊') pass continue

以下是pdfplumber测试效果

源文件如下

提取结果

最后补充2个免费转换的网站感觉还比较好用,关键是免费

到此这篇关于详解用python把pdf转为word方法总结的文章就介绍到这了,更多相关python把pdf转为word内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!