如何利用python将pdf文档转为word?

1.前言

有些时候,我们需要将pdf文档转换为word文档进行处理,但市面上的一些pdf软件往往需要付费才能使用。那么作为一名技术人员,如何才能实现pdf转word自由?

2.准备工作

提前安装好python的环境,并且安装对应的第三方包:

pip install pdf2docx

3.实现方法

3.1 convert方法

from pdf2docx import Converter

#需要转的pdf文件
pdf_file_path=r'test.pdf'
#输出的word文档
out_file_path=r'test.docx'
#进行转换
new_converter=Converter(pdf_file_path)
new_converter.convert(out_file_path)
new_converter.close()

3.2 parse方法

from pdf2docx import parse

#需要转的pdf文件
pdf_file_path=r'test.pdf'
#输出的word文档
out_file_path=r'test.docx'
#对所有页面进行转换,并输出
parse(pdf_file_path, out_file_path)

3.3 仅转换其中几页

from pdf2docx import Converter

#需要转的pdf文件
pdf_file_path=r'test.pdf'
#输出的word文档
out_file_path=r'test.docx'
#进行转换
new_converter=Converter(pdf_file_path)
#从第四页转换到最后一页,转换后输出
new_converter.convert(out_file_path,start=3)
#从第一页转换到第六页,转换后输出
new_converter.convert(out_file_path,end=6)
#从第四页转换到第六页,转换后输出
new_converter.convert(out_file_path,start=3,end=6)
new_converter.close()

转换其中的某些页面

#对pdf文档中的第1页、第四页和第九页就行转换,然后输出
new_converter.convert(out_file_path,pages=[0,3,8])

3.4 调用多进程

from pdf2docx import Converter

#需要转的pdf文件
pdf_file_path=r'test.pdf'
#输出的word文档
out_file_path=r'test.docx'
#进行转换
new_converter=Converter(pdf_file_path)
#进行多进程转换
new_converter.convert(out_file_path, multi_processing=True)
#指定数量
new_converter.convert(out_file_path, multi_processing=True, cpu_count=4)
new_converter.close()

3.5 处理有密码的pdf

from pdf2docx import Converter

#需要转的pdf文件
pdf_file_path=r'test.pdf'
#输出的word文档
out_file_path=r'test.docx'
#加密的pdf文档密码
pwd='pdf_2_word'
#进行转换
new_converter=Converter(pdf_file_path)
new_converter.convert(out_file_path,pwd)
new_converter.close()

3.6 将pdf转为表格

注意,本方法只能将以表格形式生成的pdf文档进行转换,不能处理含有表格的图片形式pdf文档。

from pdf2docx import Converter
import pandas as pd
pdf_file_path=r'test.pdf'
out_file_path=r'test.xlsx'

cv = Converter(pdf_file_path)
tables = cv.extract_tables()
cv.close()

# for table in tables:
#     print(table)

df=pd.DataFrame(tables[1:],columns=tables[0])
df.to_excel(out_file_path,encoding='utf-8-sig')
print(df)

4.后记

以上就是pdf转为word的方法,可以根据个人的情况进行调整。希望能够帮助到你~

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年8月4日
下一篇 2023年8月4日

相关推荐