阅读文本大概须要 6 分钟。python
如今网上有不少文档是 pdf 格式,虽然这个格式阅读起来很方便,而且里面的内容不会乱掉,但相应的咱们就没法修改里面的内容。虽然如今市面上有不少 pdf 转 word 软件,好比 wps,但大多数的软件是要收费的,而且价格不菲。git
前些天就有人叫我帮她把 pdf 文档转成 word 的文档。由于 pdf 文档里面的内容有不少,若是所有打印的话,费用仍是挺高的。因此她想把里面的内容格式修改下,好比行间距,字间距等等。经过这样的修改,能够把文档的页数减小不少,这样就省下很多的钱。github
因而乎我就想到了利用 python 来写个程序,把 pdf 转成 word 文档。秉承着不要重复造轮子的想法,我首先在网上搜索了下。果真已经有人写好了,咱们直接拿来用就行。程序一共只有 60 行代码,使用也很是的简单,app
程序源代码ui
import os from configparser import ConfigParser from io import StringIO from io import open from concurrent.futures import ProcessPoolExecutor from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from docx import Document def read_from_pdf(file_path): with open(file_path, 'rb') as file: resource_manager = PDFResourceManager() return_str = StringIO() lap_params = LAParams() device = TextConverter( resource_manager, return_str, laparams=lap_params) process_pdf(resource_manager, device, file) device.close() content = return_str.getvalue() return_str.close() return content def save_text_to_word(content, file_path): doc = Document() for line in content.split('\n'): paragraph = doc.add_paragraph() paragraph.add_run(remove_control_characters(line)) doc.save(file_path) def remove_control_characters(content): mpa = dict.fromkeys(range(32)) return content.translate(mpa) def pdf_to_word(pdf_file_path, word_file_path): content = read_from_pdf(pdf_file_path) save_text_to_word(content, word_file_path) def main(): config_parser = ConfigParser() config_parser.read('config.cfg') config = config_parser['default'] tasks = [] with ProcessPoolExecutor(max_workers=int(config['max_worker'])) as executor: for file in os.listdir(config['pdf_folder']): extension_name = os.path.splitext(file)[1] if extension_name != '.pdf': continue file_name = os.path.splitext(file)[0] pdf_file = config['pdf_folder'] + '/' + file word_file = config['word_folder'] + '/' + file_name + '.docx' print('正在处理: ', file) result = executor.submit(pdf_to_word, pdf_file, word_file) tasks.append(result) while True: exit_flag = True for task in tasks: if not task.done(): exit_flag = False if exit_flag: print('完成') exit(0) if __name__ == '__main__': main()
首先去 github 上把项目 clone 或下载项目到本地.spa
github : https://github.com/python-fan...code
git clone git@github.com:simpleapples/pdf2word.git
而后进入项目目录,创建虚拟环境,并安装依赖。教程
pip install -r requirements.txt
最后修改 config.cfg 文件,指定存放 pdf 和 word 文件的文件夹,以及同时工做的进程数,就能够执行 python main.py。进程
具体的程序逻辑,能够去查看原文。做者都分析的很详细。ip
https://zhuanlan.zhihu.com/p/...。
本文首发于公众号「痴海」,天天分享 Python 干货,后台回复「1024」,领取 2018 最新 Python 教程。