可将PDF转为Word文件的Python库
《开源精选》是我们分享Github、Gitee等开源社区中优质项目的栏目,包括技术、学习、实用与各种有趣的内容。本期推荐的是一个可将PDF转为Word的Python库——pdf2docx。
基于 PyMuPDF 提取文本、图片、矢量等原始数据 基于规则解析章节、段落、表格、图片、文本等布局及样式 基于 python-docx 创建Word文档
主要功能
解析和创建页面布局 页边距 章节和分栏 (目前最多支持两栏布局) 页眉和页脚 [TODO]
解析和创建段落 OCR 文本 [TODO] 水平(从左到右)或竖直(自底向上)方向文本 字体样式例如字体、字号、粗/斜体、颜色 文本样式例如高亮、下划线和删除线 列表样式 [TODO] 外部超链接 段落水平对齐方式 (左/右/居中/分散对齐)及前后间距
解析和创建图片 内联图片 灰度 /RGB/CMYK 等颜色空间图片 带有透明通道图片 浮动图片(衬于文字下方)
解析和创建表格 边框样式例如宽度和颜色 单元格背景色 合并单元格 单元格垂直文本 隐藏部分边框线的表格 嵌套表格
支持多进程转换
pdf2docx 同时解析出了表格内容和样式,因此也可以作为一个表格内容提取工具。
限制目前暂不支持扫描PDF文字识别 仅支持从左向右书写的语言(因此不支持阿拉伯语) 不支持旋转的文字 基于规则的解析无法保证100%还原PDF样式
示例
安装 $ pip install pdf2docx
更新 $ pip install --upgrade pdf2docx
我们可以使用 Converter类 或包装方法 parse() 将所有/指定的 pdf 页面转换为 docx。如果 pdf 文件包含大量页面,则支持批量处理。 转换所有页面 from pdf2docx import Converter pdf_file = "/path/to/sample.pdf" docx_file = "path/to/sample.docx" # convert pdf to docx cv = Converter(pdf_file) cv.convert(docx_file) # all pages by default cv.close()
另一种使用 parse() 的方法: from pdf2docx import parse pdf_file = "/path/to/sample.pdf" docx_file = "path/to/sample.docx" # convert pdf to docx parse(pdf_file, docx_file)转换指定页面
指定页面范围 start(如果省略则从第一页开始)和 end(如果省略则到最后一页): # convert from the second page to the end (by default) cv.convert(docx_file, start=1) # convert from the first page (by default) to the third (end=3, excluded) cv.convert(docx_file, end=3) # convert from the second page and the third cv.convert(docx_file, start=1, end=3)
或者,通过以下方式设置单独的页面 pages: # convert the first, third and 5th pages cv.convert(docx_file, pages=[0,2,4])
-END-
开源协议:GPL-3.0
开源地址:https://github.com/dothinking/pdf2docx