python处理pdf实例_python实现pdf转word的例子
pdf转word的效果一般都很差,下面使用pdfminer和docx框架,前者用来读取pdf的文本内容,后者用来写到word文件中。仅作入门级参考。
例子如下:
#!/usr/bin/env python
# coding=utf-8
import sys
import os
from binascii import b2a_hex
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTTextBox, LTTextLine, LTFigure, LTImage, LTChar
from docx import Document
def _parse_toc (doc):
"""With an open PDFDocument object, get the table of contents (toc) data
[this is a higher-order function to be passed to with_pdf()]"""
toc = []
try:
outlines = doc.get_outlines()
for (level,title,dest,a,se) in outlines:
toc.append( (level, title) )
except PDFNoOutlines:
pass
return toc
def with_pdf (pdf_doc, fn, pdf_pwd, *args):
"""Open the pdf document, and apply the function, returning the results"""
result = None
try:
# open the pdf file
fp = open(pdf_doc, 'rb')
# create a parser object associated with the file object
parser = PDFParser(fp)
# create a PDFDocument object that stores the document structure
doc = PDFDocument(parser, pdf_pwd)
# connect the parser and document objects
parser.set_document(doc)
# supply the password for initialization
if doc.is_extractable:
# apply the function and return the result
result = fn(doc, *args)
# close the pdf file
fp.close()
except IOError:
# the file doesn't exist or similar problem
pass
return result
def get_toc (pdf_doc, pdf_pwd=''):
"""Return the table of contents (toc), if any, for this pdf file"""
return with_pdf(pdf_doc, _parse_toc, pdf_pwd)
def write_file (folder, filename, filedata, flags='w'):
"""Write the file data to the folder and filename combination
(flags: 'w' for write text, 'wb' for write binary,
use 'a' instead of 'w' for append)"""
result = False
if os.path.isdir(folder):
try:
file_obj = open(os.path.join(folder, filename), flags)
file_obj.write(filedata)
file_obj.close()
result = True
except IOError:
pass
return result
def determine_image_type (stream_first_4_bytes):
"""Find out the image file type based on the magic number comparison
of the first 4 (or 2) bytes"""
file_type = None
bytes_as_hex = b2a_hex(stream_first_4_bytes)
if bytes_as_hex.startswith('ffd8'):
file_type = '.jpeg'
elif bytes_as_hex == '89504e47':
file_type = '.png'
elif bytes_as_hex == '47494638':
file_type = '.gif'
elif bytes_as_hex.startswith('424d'):
file_type = '.bmp'
return file_type
def save_image (lt_image, page_number, images_folder):
"""Try to save the image data from this LTImage object,
and return the file name, if successful"""
result = None
if lt_image.stream:
file_stream = lt_image.stream.get_rawdata()
if file_stream:
file_ext = determine_image_type(file_stream[0:4])
if file_ext:
file_name = ''.join([str(page_number), '_', lt_image.name, file_ext])
if write_file(images_folder, file_name, file_stream, flags='wb'):
result = file_name
return result
def to_bytestring (s, enc='utf-8'):
"""Convert the given unicode string to a bytestring,
using the standard encoding, unless it's already a bytestring"""
if s:
if isinstance(s, str):
return s
else:
return s.encode(enc)
def update_page_text_hash (h, lt_obj, pct=0.2):
"""Use the bbox x0,x1 values within pct%
to produce lists of associated text within the hash"""
x0 = lt_obj.bbox[0]
x1 = lt_obj.bbox[2]
key_found = False
for k, v in h.items():
hash_x0 = k[0]
if x0 >= (hash_x0 * (1.0-pct)) and (hash_x0 * (1.0+pct)) >= x0:
hash_x1 = k[1]
if x1 >= (hash_x1 * (1.0-pct)) and (hash_x1 * (1.0+pct)) >= x1:
# the text inside this LT* object was positioned at the same
# width as a prior series of text, so it belongs together
key_found = True
v.append(to_bytestring(lt_obj.get_text()))
h[k] = v
if not key_found:
# the text, based on width, is a new series,
# so it gets its own series (entry in the hash)
h[(x0,x1)] = [to_bytestring(lt_obj.get_text())]
return h
def parse_lt_objs (lt_objs, page_number, images_folder, text=[]):
"""Iterate through the list of LT* objects and capture the text
or image data contained in each"""
text_content = []
page_text = {}
''''k=(x0, x1) of the bbox, v=list of text strings within that bbox width (physical column)'''
for lt_obj in lt_objs:
if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
# text, so arrange is logically based on its column width
page_text = update_page_text_hash(page_text, lt_obj)
elif isinstance(lt_obj, LTImage):
# an image, so save it to the designated folder, and note its place in the text
saved_file = save_image(lt_obj, page_number, images_folder)
if saved_file:
# use html style tag to mark the position of the image within the text
text_content.append('')
else:
pass
#print >> sys.stderr, "error saving image on page", page_number, lt_obj.__repr__
elif isinstance(lt_obj, LTFigure):
''' LTFigure objects are containers for other LT* objects,
so recurse through the children'''
text_content.append(parse_lt_objs(lt_obj, page_number, images_folder, text_content))
for k, v in sorted([(key,value) for (key,value) in page_text.items()]):
# sort the page_text hash by the keys (x0,x1 values of the bbox),
# which produces a top-down, left-to-right sequence of related columns
text_content.append(''.join(v))
return '\n'.join(text_content)
def _parse_pages (doc, images_folder):
"""With an open PDFDocument object, get the pages and parse each one
[this is a higher-order function to be passed to with_pdf()]"""
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
text_content = []
for i, page in enumerate(PDFPage.create_pages(doc)):
interpreter.process_page(page)
# receive the LTPage object for this page
layout = device.get_result()
''' layout is an LTPage object which may contain child objects
like LTTextBox, LTFigure, LTImage, etc.'''
objs = parse_lt_objs(layout, (i+1), images_folder)
text_content.append(objs)
return text_content
def get_pages (pdf_doc, pdf_pwd='', images_folder='/tmp'):
"""Process each of the pages in this pdf file and
return a list of strings representing the text found in each page"""
return with_pdf(pdf_doc, _parse_pages, pdf_pwd, *tuple([images_folder]))
def remove_control_characters(content):
mpa = dict.fromkeys(range(32))
return content.translate(mpa)
def write_text_to_word(doc, content, file_path):
paragraph = doc.add_paragraph()
paragraph.add_run(content)
doc.save(file_path)
if __name__ == '__main__':
doc = Document()
for page_content in get_pages('D:/pdf/test.pdf'):
write_text_to_word(doc, unicode(page_content, "utf-8"), 'D:/pdf/test.docx')
python处理pdf实例_python实现pdf转word的例子相关推荐
- python处理pdf实例_Python程序图片和pdf上文字识别实例
实例一:先减少背景杂音,再做图片文字识别 为了提高识别率,先用opencv-python对扫描的图片做预处理(减少背景杂音),然后调用pytesseract识别图片上的文字.处理方式就是: 学习Pyt ...
- python处理pdf 层_Python处理PDF及生成多层PDF实例代码
Python提供了众多的PDF支持库,本文是在Python3环境下,试用了两个库来完成PDF的生成的功能.PyPDF对于读取PDF支持较好,但是没找到生成多层PDF的方法.Reportlab看起来更成 ...
- python处理pdf实例_Python实现读取PDF文件案例
最近有一个本地客户需求是读取PDF文件,然后做自动化处理.这其实是一种典型的RPA自动化需求,简单而言就是模拟人工来操作文件,网页,客户端系统等,只要操作规则定义清楚,就可以实施这种RPA应用,而如果 ...
- python读取pdf文件_python读取pdf文件
广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 一.安装pdfminer3k模块?二. 读取pdf文件import sysimp ...
- 用python汇总pdf文件_Python处理PDF文件-简译与总结
最近看到一篇介绍Python中pyPDF模块的文章,详细介绍了使用pyPDF模块获取PDF文件信息,合并拆分PDF文件等功能.很方便,在此搬运分享以下: 全文介绍了以下几方面的功能 提取文件信息 旋转 ...
- python读取pdf表格_Python 解析 PDF 表格?
需要 该公司的PDF年报包含了各种表,这些表需要在一些特定字幕下解析,称为数据结构. 解决方案 通过查看别人写的博客,我们发现在Python中通常有四种PDF解析: Pdfminer善于分析文字,这种 ...
- python不可以处理pdf文件_Python处理PDF文件-简译与总结
最近看到一篇介绍Python中pyPDF模块的文章,详细介绍了使用pyPDF模块获取PDF文件信息,合并拆分PDF文件等功能.很方便,在此搬运分享以下: 全文介绍了以下几方面的功能 提取文件信息 旋转 ...
- python闭包应用实例_Python中的闭包详细介绍和实例
一.闭包 来自wiki: 闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数.这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外 ...
- python接口脚本实例_python图形用户接口实例详解
本文实例为大家分享了python图形用户接口实例的具体代码,供大家参考,具体内容如下 运用tkinter图形库,模拟聊天应用界面,实现信息发送. from tkinter import * impor ...
最新文章
- 苹果CMS V10 播放记录_苹果cms新手入门安装配置教程
- mysql 定时同步数据_MySQL数据同步之otter
- hdu 2255二分图最大权值匹配的KM 算法
- Dubbo(四)之xml配置方式
- mysql不同版本会覆盖吗,[mysql不同版本数据库同步]mysql数据库主从同步,master和slave上的mysql必须版本一样吗,如果不一样会有什么结果?...
- linux 7查内核,查看CentOS7内核版本及发行版本
- idea 开启Run DashBoard
- java泛型_Java核心知识 基础五 JAVA 泛型
- .png图片 阴影效果(fliter:drop-shadow属性)案例
- 【6.13-6.27推荐享大礼】华为云·云享专家推荐有礼活动火热进行中……
- SQL Server 默认跟踪 -- 捕获事件详解
- docker~aspnetcore2.0镜像缺少libgdiplus问题
- linux系统日志message 分析,Linux系统日志及日志分析
- hexo-theme-icarus配置 valine 评论系统
- 计算机唤醒休眠蓝屏,分享win10睡眠唤醒就蓝屏的解决办法
- 北京大学计算机研究生怎么样,北京大学计算机专业在职研究生怎么样?
- [原创]四大开源3d游戏引擎探究(前言上)
- 使用RTT代替UART,把你的JLink变成串口调试助手~
- 数据库求候选码的算法
- The maximum number of apps for free development profiles has been reached.
热门文章
- “理了么”app使用体验
- (后端)SpringMVC提交数组时不能超过256个值(转)
- 深入hibernate的三种状态
- IE8中伪元素动态作用样式不重绘bug记录
- 超34款吸费手机被曝光下架 天语TCL大显等在其中
- 1-springboot基础
- java package 目录_修改jar包package目录结构操作方法
- 无线鼠标可以强制配对_酷冷至尊MM831三模游戏鼠标评测
- linux kernel基本构成的内容有下列哪些项_Linux内核线程kernel thread详解
- mysql抽屉图标_React Native自定义组件实现抽屉菜单控件效果