翻譯|使用教程|編輯:吉煒煒|2025-03-21 10:12:49.647|閱讀 101 次
概述:解析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@fc6vip.cn
文章轉載自:慧都網