解析PDF意味着从 PDF 文件中提取结构化或非结构化数据。由于 PDF 的结构复杂,因此这可能具有挑战性。与纯文本或JSON和XML等结构化格式不同,PDF 存储内容的方式并不总是遵循线性顺序。提取文本、表格、图像和元数据需要可靠、准确且高效的 Python PDF 解析器库。在本文中,我们将学习如何使用 Aspose.PDF for Python 在 Python 中解析 PDF。在本指南结束时,您将能够使用 Python 从 PDF 文档中提取文本、表格和图像。本文涵盖以下主题:
- Aspose.PDF:优秀的 Python PDF 解析器库
- 使用 Python 解析 PDF 并提取文本
- 如何使用 Python 解析 PDF 中的表格
- 解析 PDF 元数据:使用 Python 获取 PDF 文件信息
- 使用 Python 解析 PDF 中的图像
- 如何在 Python 中解析 PDF 注释
Aspose.PDF:优秀的 Python PDF 解析器库
Aspose.PDF for Python是目前优选的 Python PDF 解析器库之一。它提供高精度、支持结构化数据提取,甚至可以通过 OCR 支持处理扫描的 PDF。
Aspose.PDF 在 Python PDF 解析器库中脱颖而出,原因如下:
- 高精度:精确提取文本和表格。
- 支持结构化数据:适用于表格、图像和元数据。
- 无外部依赖:轻量级、独立的库。
- 多种输出格式:将 PDF 转换为文本、XLSX、DOCX、HTML 和图像格式。
- 安全性和可靠性:处理复杂的 PDF 结构而不会损坏数据。
与开源替代品相比,Aspose.PDF 提供了更强大、功能更丰富的解决方案,使其成为企业应用程序和文档自动化系统的理想选择。
安装和设置
安装 Aspose.PDF for Python 很简单。从版本中下载或运行以下pip命令:
pip install aspose-pdf
要在 Python 应用程序中开始使用 Aspose.PDF,请导入必要的模块:
import aspose.pdf as ap
提取文本:使用 Python 解析 PDF
从 PDF 解析文本是 Python PDF 解析器库的主要功能之一。我们可以从 PDF 文档的所有页面或 PDF 文档的特定页面或区域中提取文本。在接下来的部分中,我们将学习如何:
- 使用 Python 对 PDF 的所有页面进行文本解析
- 解析 PDF 中特定页面的文本
- 解析 PDF 中特定区域的文本
- 从多列 PDF 中提取文本
- 使用 ScaleFactor 增强文本解析
- 解析 PDF 中的文本:替代方法
使用 Python 解析 PDF 所有页面的文本
DocumentAspose.PDF for Python 提供了一种使用和类从 PDF 文档中提取文本的有效方法TextAbsorber。Document类用于加载 PDF 文件,而TextAbsorber类负责从所有页面中提取文本内容。该accept()方法处理每个页面并提取文本,然后可以根据需要存储或显示文本。
使用 Python 从 PDF 所有页面提取文本的步骤
- 使用该类加载 PDF 文档Document。
- 创建TextAbsorber类的一个实例来处理文本提取。
- accept()在集合上调用该方法pages,允许TextAbsorber处理所有页面。
- text使用实例的属性检索提取的文本TextAbsorber。
- 打印提取的文本。
以下代码示例展示了如何使用 Python 解析 PDF 所有页面的文本。
# This code example shows how to extract text from all pages of a PDF document in Python import aspose.pdf as ap # Open PDF document document = ap.Document("AddText.pdf") # Create text absorber text_absorber = ap.text.TextAbsorber() # Call the accept method to process all pages document.pages.accept(text_absorber) # Retrieve the extracted text extracted_text = text_absorber.text # Define the file path file_path = "extracted-text.txt" # Open the file in write mode and write the extracted text with open(file_path, "w", encoding="utf-8") as tw: tw.write(extracted_text + "\n") # Write the extracted text with a newline
解析 PDF 中特定页面的文本
我们还可以通过稍微修改之前的方法从 PDF 文档的特定页面中提取文本。您无需处理整个文档,只需在对象accept()的所需页面上调用该方法Document即可。只需使用其索引指定页码,Aspose.PDF 就会仅从该页面提取文本。此方法在处理大型 PDF 时非常有用,因为您只需要特定部分的数据,从而提高效率和性能。
以下代码示例展示了如何使用 Python 解析 PDF 特定页面的文本。
# This code example shows how to extract text from a specific page of a PDF document in Python import aspose.pdf as ap # Open PDF document document = ap.Document("AddText.pdf") # Create text absorber text_absorber = ap.text.TextAbsorber() # Call the accept method to process all pages document.pages[1].accept(text_absorber) # Retrieve the extracted text extracted_text = text_absorber.text # Define the file path file_path = "extracted-text.txt" # Open the file in write mode and write the extracted text with open(file_path, "w", encoding="utf-8") as tw: tw.write(extracted_text + "\n") # Write the extracted text with a newline
解析 PDF 中特定区域的文本
有时,我们可能需要从 PDF 页面的特定部分提取文本,而不是从整个文档中检索内容。要定位特定区域,请使用Rectangle的属性TextSearchOptions。此属性接受一个Rectangle对象,该对象定义所需区域的坐标。通过指定此边界,我们可以仅从选定区域提取文本,而忽略页面的其余内容。
从特定页面区域提取文本的步骤
- 使用该类加载 PDF 文档Document。
- 创建一个TextAbsorber类实例来从文档中捕获文本。
- 使用 定义目标区域* TextSearchOptions.Rectangle,指定从中提取文本的区域。
- accept()通过调用选定页面上的方法将文本提取应用于特定页面。
- Text从的属性中检索提取的文本TextAbsorber。
- 根据需要处理输出。
以下代码示例展示如何使用 Python 解析 PDF 页面特定区域的文本。
# This code example shows how to extract text from a specific region of a page in a PDF document using Python import aspose.pdf as ap # Open PDF document document = ap.Document("sample.pdf") # Create TextAbsorber object to extract text absorber = ap.text.TextAbsorber() absorber.text_search_options.limit_to_page_bounds = True absorber.text_search_options.rectangle = ap.Rectangle(100, 200, 250, 350, True) # Accept the absorber for the first page document.pages[1].accept(absorber) # Get the extracted text extracted_text = absorber.text # Define the file path file_path = "extracted-text.txt" # Open the file in write mode and write the extracted text with open(file_path, "w", encoding="utf-8") as tw: tw.write(extracted_text + "\n") # Write the extracted text with a newline
这种方法允许您从表格单元格、表单字段或页面的任何定义部分中精确地提取文本,使其成为文档自动化和数据分析的理想选择。
从多列 PDF 中提取文本
PDF 文档通常包含文本、图片、注释、附件和图表等多种元素。处理多列 PDF 时,提取文本并保持原始布局可能具有挑战性。
Aspose.Pdf for Python 简化了此过程,允许开发人员在提取之前操作文本属性。通过调整字体大小然后提取文本,您可以获得更清晰、更结构化的输出。以下步骤演示了如何应用此方法从多列 PDF 中准确提取文本。
使用 Python 从多列 PDF 中提取文本的步骤
- 使用该类加载 PDF 文档Document。
- 创建一个实例来TextFragmentAbsorber从文档中定位并提取单个文本片段。
- 检索所有检测到的文本片段并将其字体大小缩小70%以提高提取准确性。
- 将修改后的文档存储在内存流中,以避免保存中间文件。
- 从内存流加载PDF来处理调整后的文本。
- 使用TextAbsorber从修改后的文档中检索结构化文本。
- 将提取的文本保存到.txt文件中以供进一步使用。
以下代码示例显示如何在保留布局的同时从多列 PDF 中提取文本。
# This code example shows how to extract text from a multi-column PDF in Python import io import aspose.pdf as ap # Open PDF document document = ap.Document("multi-column-sample.pdf") # Create TextFragmentAbsorber object to extract text text_fragment_absorber = ap.text.TextFragmentAbsorber() # Accept the absorber for the first page document.pages.accept(text_fragment_absorber) # Get the collection of extracted text fragments text_fragment_collection = text_fragment_absorber.text_fragments # Reduce font size by at least 70% to improve text extraction for text_fragment in text_fragment_collection: text_fragment.text_state.font_size *= 0.7 # Save the modified document to an in-memory stream source_stream = io.BytesIO() document.save(source_stream) # Reload the document from the memory stream source_stream.seek(0) dest_document = ap.Document(source_stream) # Initialize TextAbsorber to extract the updated text text_absorber = ap.text.TextAbsorber() dest_document.pages.accept(text_absorber) extracted_text = text_absorber.text # Save the extracted text to a file with open("ExtractColumnsText_out.txt", "w", encoding="utf-8") as file: file.write(extracted_text)
该方法可确保从多列 PDF中提取的文本尽可能准确地保留其原始布局。
使用 ScaleFactor 增强文本解析
Aspose.Pdf for Python 允许您解析 PDF 并使用高级文本提取选项(例如文本格式化模式和比例因子)从特定页面提取文本。这些选项有助于从复杂的 PDF(包括多列文档)中准确提取文本。
通过使用ScaleFactor选项,我们可以微调内部文本网格以获得更高的准确性。1到 0.1之间的比例因子的作用类似于字体缩小,有助于正确对齐提取的文本。0.1到 -0.1之间的值被视为零,可根据页面上最常用字体的平均字形宽度自动缩放。如果未设置ScaleFactor ,则应用默认值1.0,确保不进行缩放调整。对于大规模文本提取,ScaleFactor = 0建议使用自动缩放(),但手动设置ScaleFactor = 0.5可以增强复杂布局的结果。但是,不必要的缩放不会影响内容完整性,确保提取的文本仍然可靠。
使用比例因子从特定页面提取文本的步骤
- 使用该类加载 PDF 文档Document。
- 创建一个实例来TextAbsorber提取文本。
- 设置TextExtractionOptions为PURE格式模式,以便准确提取。
- 调整scale_factor以优化多列 PDF 中的文本识别。
- 调用accept()集合pages来提取文本。
- 将提取的内容保存在文本文件中。
# This code example shows how to extract text from a specific region of a page in a PDF document using Python import aspose.pdf as ap # Open PDF document document = ap.Document("sample.pdf") # Initialize TextAbsorber with text extraction options text_absorber = ap.text.TextAbsorber() # Set extraction options extraction_options = ap.text.TextExtractionOptions(ap.text.TextExtractionOptions.TextFormattingMode.PURE) extraction_options.scale_factor = 0.5 # Adjusts text recognition for better column detection text_absorber.extraction_options = extraction_options # Extract text from the specified page document.pages.accept(text_absorber) # Get extracted text extracted_text = text_absorber.text # Save extracted text to a file with open("ExtractTextUsingScaleFactor_out.txt", "w", encoding="utf-8") as file: file.write(extracted_text)
如何使用 Python 解析 PDF 中的表格
解析 PDF 中的表格对于数据分析、自动化和报告至关重要。PDF 通常包含表格形式的结构化数据,使用标准文本提取方法检索这些数据可能具有挑战性。幸运的是,Aspose.Pdf for Python提供了一种强大的方法来高精度地提取表格,同时保留其结构和内容。
该类TableAbsorber专门用于检测和提取 PDF 页面中的表格。它处理每个页面、识别表格并检索各个行和单元格,同时保持其结构。以下是使用 Aspose.PDF for Python 从 PDF 文档中提取表格的步骤。
使用 Python 解析 PDF 表格的步骤
- 使用该类加载包含表格的 PDF 文件Document。
- 循环遍历pages文档集合以单独处理每一页。
- 创建类的实例TableAbsorber来检测和提取表。
- 调用该visit()方法来识别当前页面上的表格。
- 遍历提取的表的列表并检索行和单元格。
- 访问text_fragments每个单元格并使用该属性提取文本segments。
- 保存提取的表数据以供进一步分析或在控制台中显示。
# This code example shows how to extract tables from a PDF document in Python import aspose.pdf as ap # Load PDF file document = pdf.Document("sample.pdf") # Process all pages for page in document.pages: # Initialize TableAbsorber object absorber = ap.text.TableAbsorber() # Identify tables on the current page absorber.visit(page) # Loop through extracted tables for table in absorber.table_list: # Iterate through all the rows in the table for row in table.row_list: # Iterate through all the columns in the row for cell in row.cell_list: # Fetch the text fragments text_fragment_collection = cell.text_fragments # Iterate through the text fragments for fragment in text_fragment_collection: # Print the text print(fragment.text)
通过遵循这些步骤,您可以有效地从 PDF 中提取表格,从而更轻松地处理和分析结构化数据。
解析 PDF 元数据:使用 Python 获取 PDF 文件信息
处理 PDF 时,通常需要检索元数据,例如作者、创建日期、关键字和标题。Aspose.Pdf for Python通过类的属性提供对DocumentInfo对象的访问,使此操作变得简单。这允许您以编程方式提取基本文档属性。InfoDocument
解析 PDF 元数据的步骤
- 使用该类Document打开所需的 PDF 文件。
- 使用属性检索DocumentInfoinfo对象。
- 访问特定详细信息,如作者、创作日期、标题、主题和关键字。
- 打印元数据或保存以供进一步处理。
以下 Python 脚本演示了如何使用 Python 从 PDF 文件中检索并显示关键详细信息:
# This code example shows how to extract file information in Python import aspose.pdf as ap # Load the PDF document document = ap.Document("Sample.pdf") # Retrieve document information doc_info = document.info # Display document metadata print(f"Author: {doc_info.author}") print(f"Creation Date: {doc_info.creation_date}") print(f"Keywords: {doc_info.keywords}") print(f"Modify Date: {doc_info.mod_date}") print(f"Subject: {doc_info.subject}") print(f"Title: {doc_info.title}")
使用 Python 解析 PDF 文件中的图像
我们可以解析 PDF 文档并高效地检索文档中嵌入的图像。我们可以从特定页面中提取高质量图像并单独保存以供进一步使用。
每个PDF 页面将其图像存储在资源集合中,具体来说是在XImage集合内。要提取图像,请访问所需页面,Images使用其索引从集合中检索图像,然后保存。
使用 Python 解析 PDF 中的图像的步骤
- 使用该类加载包含图像的 PDF 文件Document。
- 检索您想要从中提取图像的特定页面。
- 访问Images页面的集合resources并指定图像索引。
- 使用流保存提取的图像。
以下代码示例展示了如何使用 Python 解析 PDF 中的图像。
# This code example shows how to extract images from a PDF in Python import aspose.pdf as ap # Open document document = ap.Document("Sample.pdf") # Extract a particular image (first image from the first page) x_image = document.pages[1].resources.images[1] # Define the output image path output_image_path = "OutputImage.jpg" # Save the extracted image with open(output_image_path, "wb") as output_image: output_image.write(x_image.to_stream().read())
此方法提供了一种简单而有效的方法来从 PDF 中提取图像,同时保持其质量。使用 Aspose.PDF for Python,您可以自动提取各种应用程序的图像,例如文档处理、数据存档和内容分析。
如何在 Python 中解析 PDF 注释
PDF 中的注释通过添加高亮、图形和便签来增强文档交互。每种注释类型都有特定的用途,而Aspose.Pdf for Python可以轻松提取它们进行分析或处理。
- 使用 Python 解析 PDF 中的文本注释
- 使用 Python 解析 PDF 中突出显示的文本
- 使用 Python 解析 PDF 图形注释
- 如何在 Python 中解析 PDF 链接注释
使用 Python 解析 PDF 中的文本注释
PDF 文档通常包含文本注释,这些注释可作为注释或说明附加到页面上的特定位置。折叠时,这些注释显示为图标,展开时,它们会在弹出窗口中显示文本。PDF 中的每个页面都有自己的注释集合,其中包含特定于该页面的所有注释。通过利用Aspose.PDF for Python,您可以有效地从 PDF 文件中提取文本注释。
解析 PDF 中的文本注释的步骤
- 使用该类加载PDF文档Document。
- 检索annotations特定页面的属性以获取该页面上的所有注释。
- 遍历注释并过滤带有 的注释AnnotationType.TEXT。
- 检索相关信息,如注释位置(rect),以供进一步处理或显示。
import aspose.pdf as ap # Load the PDF document document = ap.Document("annotations.pdf") # Loop through all annotations on the first page for annotation in document.pages[1].annotations: if annotation.annotation_type == ap.annotations.AnnotationType.TEXT: # Print annotation details print(f"Title: {annotation.full_name}") print(f"Contents: {annotation.contents}") print(f"Annotation Rectangle: {annotation.rect}")
通过遵循这些步骤,您可以使用 Python 高效地从 PDF 文档中提取和处理文本注释。
使用 Python 解析 PDF 中突出显示的文本
在许多情况下,您可能只需要从 PDF 中提取突出显示的文本,而不是全部内容。无论您是分析重要笔记、总结要点还是自动化文档处理,Aspose.PDF for Python 都可以轻松高效地检索突出显示的文本。
突出显示注释标记重要的文本段落,通常用于评论或学习笔记。您可以使用该类提取突出显示的文本及其属性,例如颜色和位置HighlightAnnotation。
我们可以按照前面提到的步骤来解析 PDF 文档中突出显示的文本注释。但是,我们只需AnnotationType.HIGHLIGHT在步骤 3 中提及即可。
以下示例演示如何从 PDF 中过滤和提取突出显示的文本。
import aspose.pdf as ap # Load the PDF document document = ap.Document("annotations.pdf") # Loop through all annotations on the first page for annotation in document.pages[1].annotations: if annotation.annotation_type == ap.annotations.AnnotationType.HIGHLIGHT: # Print annotation details print(f"Title: {annotation.full_name}") print(f"Annotation Rectangle: {annotation.rect}")
使用 Python 解析 PDF 图形注释
图形注释包括用于强调或解释的形状、图画或图章InkAnnotation等图形元素。提取这些注释涉及识别StampAnnotation对象并检索其绘图路径或图像。
要解析 PDF 文档中的行注释,请按照前面概述的步骤操作。唯一需要修改的是AnnotationType.LINE在步骤 3 中指定。
以下示例演示如何使用 Python 解析 PDF 中的行注释。
import aspose.pdf as ap # Load the PDF document document = ap.Document("annotations.pdf") # Loop through all annotations on the first page for annotation in document.pages[1].annotations: if annotation.annotation_type == ap.annotations.AnnotationType.LINE: # Print annotation details print(f"Annotation Rectangle: {annotation.rect}")
如何在 Python 中解析 PDF 链接注释
PDF 中的链接注释允许用户在文档内无缝导航、打开外部文件或直接从 PDF 访问网页。这些超链接通过提供对附加信息的快速访问来增强交互性并改善用户体验。
要从 PDF 中提取链接注释,请按照与之前相同的步骤操作,但在步骤 3 中,请确保指定AnnotationType.LINK。这可确保仅检索链接注释。
以下代码示例展示如何使用 Python 解析 PDF 中的链接注释。
import aspose.pdf as ap # Load the PDF document document = ap.Document("annotations.pdf") # Loop through all annotations on the first page for annotation in document.pages[1].annotations: if annotation.annotation_type == ap.annotations.AnnotationType.LINK: # Print annotation details print(f"Annotation Rectangle: {annotation.rect}")
通过利用 Aspose.PDF for Python,您可以有效地提取和操作各种用例的链接注释,例如索引文档或增强导航。
结论
Aspose.PDF for Python 是需要可靠、高效且功能丰富的 PDF 解析解决方案的开发人员的 Python PDF 解析器库。无论您需要解析文本、表格、图像、元数据还是注释,Aspose.PDF 都能提供必要的工具。