Python 读取pdf文件

Python 实现读取pdf文件简单示例。

安装命令

需要安装操作pdf的三方类库,命令如下:

bash 复制代码
pip install pdfminer3K

安装过程如下:

引入类库

需要引入很多的类库。

示例如下:

python 复制代码
import sys
import importlib
importlib.reload(sys)

from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import  PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

读取pdf实现

实现步骤为:先通过二进制方式打开测试pdf文档,创建pdf文档解析测试文档内容,

最后读取文件内容,保存到另一个文件中。

示例如下:

python 复制代码
import sys
import importlib

importlib.reload(sys)

from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import os



def read_pdf(path, toPath):
    # 以二进制方式打开pdf文件
    f = open(path, 'rb')

    # 创建一个pdf文档分析器
    parser = PDFParser(f)
    # 创建pdf文档
    pdfFile = PDFDocument()
    # 链接分析器与文档对象
    parser.set_document(pdfFile)
    pdfFile.set_parser(parser)
    # 提供初始化密码
    pdfFile.initialize()

    # 检测文档是否提供txt转换
    if not pdfFile.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 解析数据
        # 数据管理器
        manager = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(manager, laparams=laparams)
        # 解释器对象
        interpreter = PDFPageInterpreter(manager, device)
        for page in pdfFile.get_pages():
            interpreter.process_page(page)
            layout = device.get_result()
            for x in layout:
                if isinstance(x, LTTextBoxHorizontal):
                    with open(toPath, 'a', encoding='utf-8') as f:
                        print(x.get_text())
                        f.write(x.get_text() + "\n")


path = os.path.join(os.getcwd(), 'test_1.pdf')
toPath = os.path.join(os.getcwd(), 'test_2.txt')
read_pdf(path, toPath)

注意:无法读取中文,貌似需要加载中文字体。还有就是在写入pdf文件,格式不对无法打开暂时没找到原因。

总结

本篇只是使用Python 实现读取pdf文件简单示例,因为时间关系没有做深入的扩展,等之后有时间再做补充。

相关推荐
我材不敲代码1 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得03 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长4 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_192779874 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272714 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊4 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm7774 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew5 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6525 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
2301_821369615 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python