怎么在python中使用pdfminer解析pdf文件

发布时间:2021-03-25 17:13:11 作者:Leah
来源:亿速云 阅读:676

怎么在python中使用pdfminer解析pdf文件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

pdf2txt.py从PDF文件中提取所有文本内容。但不能识别画成图片的文本,这需要特征识别。对于加密的PDF你需要提供一个密码才能解析,对于没有提取权限的PDF文档你得不到任何文本。 

dumppdf.py把PDF文件内容变成pseudo-XML格式。这个程序主要用于debug,但是它也可能用于提取一些有意义的内容(比如图片)。

官方主页:https://euske.github.io/pdfminer/

其特征有:1、完全使用python编写。(适用于2.4或更新版本)2、解析,分析,并转换成PDF文档。3、PDF-1.7规范的支持。(几乎)4、中日韩语言和垂直书写脚本支持。5、各种字体类型(Type1、TrueType、Type3,和CID)的支持。6、基本加密(RC4)的支持。7、PDF与HTML转换。8、纲要(TOC)的提取。9、标签内容提取。10、通过分组文本块重建原始的布局。
如果你的Python有安装pip模块,就可以通过命令“python pip install pdfminer”,自动安装pdfminer。

解析pdf文件用到的类:

python的工具,安装当然是使用pip安装了。

pip install pdfminer

命令行方式

为了使用方便,pdfminer 提供了一个命令行工具来直接转换pdf文件,使用方法如下:

pdf2txt.py <path_to_pdf_file>

编程方式

除了命令行方式以外,对于复杂应用场景,pdfminer 也提供了以编程方式来转换 pdf 文件,主要使用下面几个类来实现:

下面看一个例子:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams
import StringIO


class PDFUtils():

  def __init__(self):
    pass

  def pdf2txt(self, path):
    output = StringIO.StringIO()
    with open(path, 'rb') as f:
      praser = PDFParser(f)

      doc = PDFDocument(praser)

      if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed

      pdfrm = PDFResourceManager()

      laparams = LAParams()

      device = PDFPageAggregator(pdfrm, laparams=laparams)

      interpreter = PDFPageInterpreter(pdfrm, device)

      for page in PDFPage.create_pages(doc):
        interpreter.process_page(page)
        layout = device.get_result()
        for x in layout:
          if hasattr(x, "get_text"):
            content = x.get_text()
            output.write(content)

    content = output.getvalue()
    output.close()
    return content


if __name__ == '__main__':
  path = u'/tmp/abc.pdf'
  pdf_utils = PDFUtils()
  print pdf_utils.pdf2txt(path)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. js在页面中嵌入pdf文件
  2. 怎么在Python 3.6 中利用pdfminer对pdf文件进行解析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

pdfminer python pdf

上一篇:如何在Mint UI中使用CheckList组件库

下一篇:怎么在spring boot中利用sonarqube检查技术债务

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》