随笔- 310  文章- 1  评论- 0  阅读- 85655 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
# pip3 install pdfminer3k
  
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBoxHorizontal
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, PDFTextExtractionNotAllowed
from pdfminer.pdfdevice import PDFDevice
 
def read_pdf(pdf_name, result_name):
    # 以二进制读模式打开
    fp = open(pdf_name, 'rb')
    # 用文件对象来创建一个pdf文档分析器
    parser = PDFParser(fp)
    # 创建一个pdf文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    parser.set_document(doc)
    doc.set_parser(parser)
    # 提供初始密码,如果没有密码 就创建一个空的字符串
    doc.initialize('')
    # 检测文档是否提供txt转换,不提供就抛出异常
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    # 创建PDf 资源管理器 来管理共享资源
    rsrcmgr = PDFResourceManager()
    # 创建一个PDF设备对象
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    # 创建一个PDF解释器对象
    interpreter = PDFPageInterpreter(rsrcmgr, device)
     
    with open(result_name,"w",encoding="u8") as fd_out:
        # 循环遍历列表,每次处理一个page的内容
        for i,page in enumerate(doc.get_pages(),1):
            index = "===========《第{}页》===========".format(i)
            print(index)
            fd_out.write(index + "\n")
            interpreter.process_page(page)
            # 接受该页面的LTPage对象
            layout = device.get_result()
            for x in layout:
                # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 一般包括LTTextBox,
                # LTFigure, LTImage, LTTextBoxHorizontal 等等 想要获取文本就获得对象的text属性
                if not isinstance(x, LTTextBoxHorizontal):
                    continue
                results = x.get_text()
                print(results)
                fd_out.write(results)   
 
                         
 
if __name__ == '__main__':
    pdf_name = 'test.pdf'
    result = 'test.txt'
    read_pdf(pdf_name, result)

  

 posted on   boye169  阅读(2573)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示