<p style=
"line-height: 1.75em;"
><span style=
"font-family: 微软雅黑, "Microsoft YaHei";"
> 1
#-*- coding: UTF-8 -*-
2
#!/usr/bin/python
3
# -*- coding: utf-8 -*-
4
5import sys
6import importlib
7importlib.reload(sys)
8
9from pdfminer.pdfparser import PDFParser,PDFDocument
10from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
11from pdfminer.converter import PDFPageAggregator
12from pdfminer.layout import *
13from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
14import os
15
16
#设置工作目录文件夹
17os.chdir(r
'c:/users/dicey/desktop/codes/pdf-docx'
)
18
19
''
'
20解析pdf文件,获取文件中包含的各种对象
21'
''
22
# 解析pdf文件函数
23def parse(pdf_path):
24 fp = open(
'diya.pdf'
,
'rb'
)
# 以二进制读模式打开
25
# 用文件对象来创建一个pdf文档分析器
26 parser = PDFParser(fp)
27
# 创建一个PDF文档
28 doc = PDFDocument()
29
# 连接分析器 与文档对象
30 parser.set_document(doc)
31 doc.set_parser(parser)
32
33
# 提供初始化密码
34
# 如果没有密码 就创建一个空的字符串
35 doc.initialize()
36
37
# 检测文档是否提供txt转换,不提供就忽略
38
if
not doc.is_extractable:
39 raise PDFTextExtractionNotAllowed
40
else
:
41
# 创建PDf 资源管理器 来管理共享资源
42 rsrcmgr = PDFResourceManager()
43
# 创建一个PDF设备对象
44 laparams = LAParams()
45 device = PDFPageAggregator(rsrcmgr, laparams=laparams)
46
# 创建一个PDF解释器对象
47 interpreter = PDFPageInterpreter(rsrcmgr, device)
48
49
# 用来计数页面,图片,曲线,figure,水平文本框等对象的数量
50 num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0
51
52
# 循环遍历列表,每次处理一个page的内容
53
for
page
in
doc.get_pages():
# doc.get_pages() 获取page列表
54 num_page += 1
# 页面增一
55 interpreter.process_page(page)
56
# 接受该页面的LTPage对象
57 layout = device.get_result()
58
for
x
in
layout:
59
if
isinstance(x,LTImage):
# 图片对象
60 num_image += 1
61
if
isinstance(x,LTCurve):
# 曲线对象
62 num_curve += 1
63
if
isinstance(x,LTFigure):
# figure对象
64 num_figure += 1
65
if
isinstance(x, LTTextBoxHorizontal):
# 获取文本内容
66 num_TextBoxHorizontal += 1
# 水平文本框对象增一
67
# 保存文本内容
68
with
open(r
'test2.doc'
,
'a'
,encoding=
'utf-8'
) as f:
#生成doc文件的文件名及路径
69 results = x.get_text()
70 f.write(results)
71 f.write(
'\n'
)
72 print(
'对象数量:\n'
,
'页面数:%s\n'
%num_page,
'图片数:%s\n'
%num_image,
'曲线数:%s\n'
%num_curve,
'水平文本框:%s\n'
73 %num_TextBoxHorizontal)
74
75
76if __name__ ==
'__main__'
:
77 pdf_path = r
'diya.pdf'
#pdf文件路径及文件名
78 parse(pdf_path)<br></span></p>