您的位置:首页技术文章
文章详情页

详解用Python把PDF转为Word方法总结

【字号: 日期:2022-06-21 09:15:48浏览:28作者:猪猪

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

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

详解用Python把PDF转为Word方法总结

# pip install pdf2docx #安装依赖库from pdf2docx import Converterpdf_file = r’C:UsersAdministratorDesktop新建文件夹mednine.pdf’docx_file = r’C:UsersAdministratorDesktopPython教程02.docx’# convert pdf to docxcv = 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, PDFPageInterpreterfrom pdfminer.converter import TextConverterfrom pdfminer.layout import LAParamsfrom pdfminer.pdfpage import PDFPagefrom io import StringIOimport sysimport stringfrom docx import Documentdef 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 textdef 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:UsersmaynDesktop程序临时培训教材.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 pdfplumberimport pandas as pdimport timefrom time import ctimeimport psutil as ps #import threadingimport gcpdf = pdfplumber.open(r'C:UsersAdministratorDesktop新建文件夹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:UsersAdministratorDesktop新建文件夹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(’nnn’) time.sleep(5)def dojob1(): #此函数 直接循环提取PDF里面各个页面的表格 print(’*********************’) for i in range(0,N):pdf2exl(i)

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

import camelotimport wand# 从PDF文件中提取表格def output(i): #print(tables) #for i in range(5): tables = camelot.read_pdf(r’C:UsersAdministratorDesktop新建文件夹mednine.pdf’, pages=str(i), flavor=’stream’) print(tables[i]) # 表格数据 print(tables[i].data)tables[i].to_csv(r’C:UsersAdministratorDesktop新建文件夹002’+str(i)+r’.csv’)def plotpdf():# 这个是画pdf 结构的函数 现在不能用 不要打开#print(tables[0]) tables = camelot.read_pdf(r’C:UsersmaynDesktopvcode工作区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

以下是pdfplumber测试效果

源文件如下

详解用Python把PDF转为Word方法总结

提取结果

详解用Python把PDF转为Word方法总结

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

http://pdfdo.com/pdf-to-word.aspx

http://app.xunjiepdf.com/pdf2word/

到此这篇关于详解用Python把PDF转为Word方法总结的文章就介绍到这了,更多相关Python把PDF转为Word内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: python
相关文章: