简体   繁体   English

如何使用 Python 从 PDF 中的特定区域提取文本?

[英]How to extract text from a Specific Area in a PDF using Python?

I'm trying to extract Text from a PDF using Python, and I have successfully done so using PyPDF2 like this:我正在尝试使用 Python 从 PDF 中提取文本,并且我已经成功地使用 PyPDF2 这样做了,如下所示:

import PyPDF2
pdfFileObj = open('path', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(0)
pageObj.extractText()

This extracts all the Text from the Page, but I want to extract the text only from a Rectangular region of 3'x4' at the top-left part of the page.这将从页面中提取所有文本,但我只想从页面左上角的 3'x4' 矩形区域中提取文本。

I Basically want to do something like : How-to extract text from a pdf doc within a specific rectangular region?我基本上想做类似的事情: 如何从特定矩形区域内的 pdf 文档中提取文本? but in Python但在 Python 中

Can this be done by PyPDF2 or by any other Python Library?这可以由 PyPDF2 或任何其他 Python 库完成吗?

This is a rather complex topic, but it is possible.这是一个相当复杂的话题,但这是可能的。 First you need to get familiar with the pdf format descripton.首先你需要熟悉pdf格式的描述。

Start here for example.例如,从这里开始。

You can identify the location and contents of the text boxes and extract the string data.您可以识别文本框的位置和内容并提取字符串数据。

This topic holds examples for pyPdf, the previous version of PyPDF2, but syntax is similar. 主题包含 pyPdf(PyPDF2 的先前版本)的示例,但语法类似。 There are examples on how to iterate through the indirect objects.有关于如何遍历间接对象的示例。

A good place to start is also the source of the function pageObj.extractText() that you used.一个很好的起点也是您使用的函数pageObj.extractText()的来源。

If you are not restricted to Python: How to extract text from a PDF?如果您不限于 Python: 如何从 PDF 中提取文本?

You can also use a tool like iText RUPS to inspect the pdf.您还可以使用iText RUPS 之类的工具来检查 pdf。 It shows how the content is rendered and placed on the page:它显示了内容是如何呈现和放置在页面上的:

在此处输入图片说明

Afterwards you should be able to identify and address the elements and extract their content.之后,您应该能够识别和处理元素并提取其内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM