使用pdfminer实现pdf文件的布局分析 python

参考资料:

https://github.com/euske/pdfminer

https://stackoverflow.com/questions/22898145/how-to-extract-text-and-text-coordinates-from-a-pdf-file?noredirect=1

import cv2
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
import pdfminer
import numpy as np
import matplotlib.pyplot as plt
from pdf2image import convert_from_path image_path = 'literature.pdf' layout_type = ['LTTextBox', 'LTFigure', 'LTImage', 'LTCurve', 'LTRect']
# Text:红色, Figure:绿色, Image:蓝色, Curve:黄色, Rect:紫色
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (160, 32, 240)] draw_color = dict(zip(layout_type, color)) def parse_obj(lt_objs): boxs = {x: [] for x in layout_type}
# loop over the object list
for obj in lt_objs: if isinstance(obj, pdfminer.layout.LTTextBoxHorizontal):
boxs['LTTextBox'].append(obj.bbox)
elif isinstance(obj, pdfminer.layout.LTFigure):
boxs['LTFigure'].append(obj.bbox)
elif isinstance(obj, pdfminer.layout.LTImage):
boxs['LTImage'].append(obj.bbox)
elif isinstance(obj, pdfminer.layout.LTCurve):
boxs['LTCurve'].append(obj.bbox)
elif isinstance(obj, pdfminer.layout.LTRect):
boxs['LTRect'].append(obj.bbox)
else:
raise
return boxs # Open a PDF file.
fp = open(image_path, 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
password = '123'
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager() # Set parameters for analysis.
laparams = LAParams()
# Create a PDF page aggregator object.
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device) page_boxs = []
for page in PDFPage.create_pages(document):
interpreter.process_page(page)
# receive the LTPage object for the page.
layout = device.get_result()
# extract text from this object
boxs = parse_obj(layout._objs)
page_sized = tuple([round(i) for i in layout.bbox])
page_boxs.append((page_sized, boxs))
pass image = convert_from_path(image_path) assert len(image) == len(page_boxs), "The number of boxes doesn't match the number of pictures"
for i in range(len(image)):
# 得到这一页图片
image_pil = image[i]
# 把这一页的图片格式转成numpy类型
image_numpy = np.array(image_pil)
# 得到这一页图片德国高度,为了之后得到实际的box
page_boxs_height = page_boxs[i][0][3]
print(page_boxs[i][1]) # 遍历这一页的框
for key, values in page_boxs[i][1].items():
# 把实际的图片大小resize到页面的大小
image_numpy = cv2.resize(image_numpy, page_boxs[i][0][2:4], interpolation=cv2.INTER_AREA)
for value in values:
# The y-coordinates are given as the distance from the bottom of the page.
real_box = (value[0], page_boxs_height-value[3], value[2], page_boxs_height-value[1])
real_box_integer = tuple([round(jj) for jj in real_box])
# 画图
cv2.rectangle(image_numpy, real_box_integer[:2], real_box_integer[2:], draw_color[key], 2)
plt.figure(), plt.imshow(image_numpy)
plt.show()

结果如下:

此代码只涉及到PDF文件的布局分析,没有涉及到PDF转成可编辑文档。供大家参考,有问题希望大家多多指正

pdfminer实现pdf布局分析 python (pdfminer realize layout analysis with PDF python)的更多相关文章

  1. PDF格式分析

    系列文章是csdn作者'秋风之刀'写的,我只是把目录列出来而已,感谢作者辛苦付出. PDF格式分析(一)简介 PDF格式分析(二)语法之对象 PDF格式分析(三)语法之Filter PDF格式分析(四 ...

  2. Python:解析PDF文本及表格——pdfminer、tabula、pdfplumber 的用法及对比

    pdf 是个异常坑爹的东西,有很多处理 pdf 的库,但是没有完美的. 一.pdfminer3k pdfminer3k 是 pdfminer 的 python3 版本,主要用于读取 pdf 中的文本. ...

  3. 从PDF中提取信息----PDFMiner

    今天由于某种原因需要将pdf中的文本提取出来,就去搜了下资料,发现PDFMiner是针对 内容提取的,虽然最后发现pdf里面的文本全都是图片,就没整成功,不过试了个文本可复制的 那种pdf文件,发现还 ...

  4. Python代码教你批量将PDF转为Word

    很多时候在学习时发现许多文档都是PDF格式,PDF格式却不利于学习使用,因此需要将PDF转换为Word文件,但或许你从网上下载了很多软件,但只能转换前五页(如WPS等),要不就是需要收费,那有没有免费 ...

  5. JFS 文件系统概述及布局分析

    JFS 文件系统概述及布局分析 日志文件系统如何缩短系统重启时间 如果发生系统崩溃,JFS 提供了快速文件系统重启.通过使用数据库日志技术,JFS 能在几秒或几分钟之内把文件系统恢复到一致状态,而非日 ...

  6. Python核心编程第二版(中文).pdf 目录整理

    python核心编程目录 Chapter1:欢迎来到python世界!-页码:7 1.1什么是python 1.2起源  :罗萨姆1989底创建python 1.3特点 1.3.1高级 1.3.2面向 ...

  7. 基于binlog来分析mysql的行记录修改情况(python脚本分析)

          最近写完mysql flashback,突然发现还有有这种使用场景:有些情况下,可能会统计在某个时间段内,MySQL修改了多少数据量?发生了多少事务?主要是哪些表格发生变动?变动的数量是怎 ...

  8. Python应用——自定义函数:分割PDF文件函数

    案例 将一个 pdf 文件按要求分割为几个部分.比如说一个pdf有20页,分成5个pdf文件,每个pdf文件包含4页.设计函数实现? Python代码 from PyPDF2 import PdfFi ...

  9. 《Python3网络爬虫开发实战》PDF+源代码+《精通Python爬虫框架Scrapy》中英文PDF源代码

    下载:https://pan.baidu.com/s/1oejHek3Vmu0ZYvp4w9ZLsw <Python 3网络爬虫开发实战>中文PDF+源代码 下载:https://pan. ...

随机推荐

  1. Centos7.4 离线安装httpd(解决rpm依赖)

    1.直接下载httpd的rpm安装包,安装失败需要先解决依赖. [root@node06 ~]# rpm -ivh httpd--.el7.centos.x86_64.rpm warning: htt ...

  2. Oracle 部门员工查询

    --部门:部门编号,部门名称,地址: --员工:员工编号,员工名字,职务,管理编号,入职日期,薪资,奖金,部门编号: CREATE TABLE dept( deptno INT PRIMARY KEY ...

  3. PHP curl_close函数

    说明 void curl_close ( resource $ch ) 关闭一个cURL会话并且释放所有资源.cURL句柄ch 也会被释放. 参数 ch 由 curl_init() 返回的 cURL ...

  4. 【HDOJ6609】Find the answer(线段树)

    题意:给定一个n个正整数的数列,第i项为w[i],对于每个i,你要从[1,i-1]中选择一些变成0,使得变化后[1,i]的总和小于m,每次询问最少要变几个 n<=2e5,m<=1e9,1& ...

  5. delphi 半透明窗体类

    {******************************************************************************* 半透明窗体控件 版本:1.0 功能说明 ...

  6. 华为交换机telnet配置

    1.在路由器上和交换机相连的借口上配置一个IP地址:比如192.168.1.1 24 2.在交换机上配置如下:<switch>system-view[switch]vlan 10[swit ...

  7. LINUX shell脚本相关

    调试脚本 测试脚本语法:bash -n file.sh 查看脚本每一步执行情况:bash -x file.sh   位置变量:$1,$2,... 特殊变量:           %?:最后一个命令的执 ...

  8. Could not resolve placeholder'XXX' in string value "XXXX"

    练习SSM项目的demo中遇到一个问题,我在applicationContext.xml中使用了<context:property-placeholder location="clas ...

  9. HDU 1028 Ignatius and the Princess III (生成函数/母函数)

    题目链接:HDU 1028 Problem Description "Well, it seems the first problem is too easy. I will let you ...

  10. maven导出工程pom文件中依赖的jar包

    在工程的pom文件里加上下面plugin, 然后执行mvn clean package -Dmaven.test.skip=true命令,就可以lib包收集起来了 <plugin> < ...