翻译|使用教程|编辑:吉炜炜|2025-03-21 10:12:49.647|阅读 6 次
概述:解析PDF意味着从 PDF 文件中提取结构化或非结构化数据。由于 PDF 的结构复杂,因此这可能具有挑战性。在本文中,我们将学习如何使用 Aspose.PDF for Python 在 Python 中解析 PDF。在本指南结束时,您将能够使用 Python 从 PDF 文档中提取文本、表格和图像。
# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>
相关链接:
解析PDF意味着从 PDF 文件中提取结构化或非结构化数据。由于 PDF 的结构复杂,因此这可能具有挑战性。与纯文本或JSON和XML等结构化格式不同,PDF 存储内容的方式并不总是遵循线性顺序。提取文本、表格、图像和元数据需要可靠、准确且高效的 Python PDF 解析器库。在本文中,我们将学习如何使用 Aspose.PDF for Python 在 Python 中解析 PDF。在本指南结束时,您将能够使用 Python 从 PDF 文档中提取文本、表格和图像。本文涵盖以下主题:
Aspose.PDF for Python是目前优选的 Python PDF 解析器库之一。它提供高精度、支持结构化数据提取,甚至可以通过 OCR 支持处理扫描的 PDF。
Aspose.PDF 在 Python PDF 解析器库中脱颖而出,原因如下:
与开源替代品相比,Aspose.PDF 提供了更强大、功能更丰富的解决方案,使其成为企业应用程序和文档自动化系统的理想选择。
安装 Aspose.PDF for Python 很简单。从版本中下载或运行以下pip命令:
pip install aspose-pdf要在 Python 应用程序中开始使用 Aspose.PDF,请导入必要的模块:
import aspose.pdf as ap
从 PDF 解析文本是 Python PDF 解析器库的主要功能之一。我们可以从 PDF 文档的所有页面或 PDF 文档的特定页面或区域中提取文本。在接下来的部分中,我们将学习如何:
DocumentAspose.PDF for Python 提供了一种使用和类从 PDF 文档中提取文本的有效方法TextAbsorber。Document类用于加载 PDF 文件,而TextAbsorber类负责从所有页面中提取文本内容。该accept()方法处理每个页面并提取文本,然后可以根据需要存储或显示文本。
以下代码示例展示了如何使用 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 文档的特定页面中提取文本。您无需处理整个文档,只需在对象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 页面的特定部分提取文本,而不是从整个文档中检索内容。要定位特定区域,请使用Rectangle的属性TextSearchOptions。此属性接受一个Rectangle对象,该对象定义所需区域的坐标。通过指定此边界,我们可以仅从选定区域提取文本,而忽略页面的其余内容。
以下代码示例展示如何使用 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 时,提取文本并保持原始布局可能具有挑战性。
Aspose.Pdf for Python 简化了此过程,允许开发人员在提取之前操作文本属性。通过调整字体大小然后提取文本,您可以获得更清晰、更结构化的输出。以下步骤演示了如何应用此方法从多列 PDF 中准确提取文本。
以下代码示例显示如何在保留布局的同时从多列 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中提取的文本尽可能准确地保留其原始布局。
Aspose.Pdf for Python 允许您解析 PDF 并使用高级文本提取选项(例如文本格式化模式和比例因子)从特定页面提取文本。这些选项有助于从复杂的 PDF(包括多列文档)中准确提取文本。
通过使用ScaleFactor选项,我们可以微调内部文本网格以获得更高的准确性。1到 0.1之间的比例因子的作用类似于字体缩小,有助于正确对齐提取的文本。0.1到 -0.1之间的值被视为零,可根据页面上最常用字体的平均字形宽度自动缩放。如果未设置ScaleFactor ,则应用默认值1.0,确保不进行缩放调整。对于大规模文本提取,ScaleFactor = 0建议使用自动缩放(),但手动设置ScaleFactor = 0.5可以增强复杂布局的结果。但是,不必要的缩放不会影响内容完整性,确保提取的文本仍然可靠。
# 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)
解析 PDF 中的表格对于数据分析、自动化和报告至关重要。PDF 通常包含表格形式的结构化数据,使用标准文本提取方法检索这些数据可能具有挑战性。幸运的是,Aspose.Pdf for Python提供了一种强大的方法来高精度地提取表格,同时保留其结构和内容。
该类TableAbsorber专门用于检测和提取 PDF 页面中的表格。它处理每个页面、识别表格并检索各个行和单元格,同时保持其结构。以下是使用 Aspose.PDF for Python 从 PDF 文档中提取表格的步骤。
# 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 时,通常需要检索元数据,例如作者、创建日期、关键字和标题。Aspose.Pdf for Python通过类的属性提供对DocumentInfo对象的访问,使此操作变得简单。这允许您以编程方式提取基本文档属性。InfoDocument
以下 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}")
我们可以解析 PDF 文档并高效地检索文档中嵌入的图像。我们可以从特定页面中提取高质量图像并单独保存以供进一步使用。
每个PDF 页面将其图像存储在资源集合中,具体来说是在XImage集合内。要提取图像,请访问所需页面,Images使用其索引从集合中检索图像,然后保存。
以下代码示例展示了如何使用 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,您可以自动提取各种应用程序的图像,例如文档处理、数据存档和内容分析。
PDF 中的注释通过添加高亮、图形和便签来增强文档交互。每种注释类型都有特定的用途,而Aspose.Pdf for Python可以轻松提取它们进行分析或处理。
PDF 文档通常包含文本注释,这些注释可作为注释或说明附加到页面上的特定位置。折叠时,这些注释显示为图标,展开时,它们会在弹出窗口中显示文本。PDF 中的每个页面都有自己的注释集合,其中包含特定于该页面的所有注释。通过利用Aspose.PDF for 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.TEXT: # Print annotation details print(f"Title: {annotation.full_name}") print(f"Contents: {annotation.contents}") print(f"Annotation Rectangle: {annotation.rect}")通过遵循这些步骤,您可以使用 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}")
图形注释包括用于强调或解释的形状、图画或图章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}")
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 都能提供必要的工具。
————————————————————————————————————————
关于慧都科技:
慧都科技是专注软件工程、智能制造、石油工程三大行业的数字化解决方案服务商。在软件工程领域,我们提供开发控件、研发管理、代码开发、部署运维等软件开发全链路所需的产品,提供正版授权采购、技术选型、个性化维保等服务,帮助客户实现技术合规、降本增效与风险可控。慧都科技Aspose在中国的官方授权代理商,提供Aspose系列产品免费试用,咨询,正版销售等于一体的专业化服务。Aspose是文档处理领域的优秀产品,帮助企业高效构建文档处理的应用程序。
下载|体验更多Aspose产品,请咨询,或拨打产品热线:023-68661681
加入Aspose技术交流QQ群(666790229),与更多小伙伴一起探讨提升开发技能。
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@wqylolg.cn
文章转载自:慧都网