跳過到頁腳內容
使用IRONPDF

如何在.NET中從PDF中提取資料

如何在 .NET 中從 PDF 擷取資料

IronPDF 讓您只需幾行程式碼,即可在 .NET 環境中輕鬆從 PDF 文件中擷取文字、表格、表單欄位及附件,非常適合用於自動化處理發票、建立知識庫,或生成報告,且無需進行複雜的解析。

PDF 文件在商業領域無所不在; 現代的例子包括發票、報告、合約和手冊。 但是,透過程式設計從中獲取關鍵資訊可能很棘手。 PDF 文件關注的是內容的呈現方式,而不是資料的存取方式。

對於 .NET 開發人員來說, IronPDF是一個功能強大的 .NET PDF 程式庫,可以輕鬆地從 PDF 文件中提取資料。 您可以直接從 PDF 文件中提取文字、表格、表單欄位、圖片及附件。 無論您是自動化處理發票、建立知識庫,還是生成報告,此函式庫都能為您節省大量時間。

本指南將透過實際範例引導您完成提取文字內容、表格資料和表單欄位值的操作,並在每個程式碼片段後進行解釋,以便您可以將其應用到自己的專案中。

如何開始使用 IronPDF?

為什麼安裝如此快速?

透過 NuGet 套件管理員安裝 IronPDF 只需幾秒鐘。 開啟軟體包管理器控制台並執行:

Install-Package IronPdf

對於 Windows 開發者而言,安裝過程十分簡單。 若您部署於 LinuxmacOS 系統,IronPDF 亦支援這些平台。 您甚至可以在 Docker 容器中執行 IronPDF,或部署至 AzureAWS

提取文字的最簡單方法是什麼?

安裝完成後,您即可立即開始處理 PDF 文件。 以下是一個簡單的 .NET 範例,展示了 IronPDF API 的簡潔性:

using IronPdf;
// Load any PDF document
var pdf = PdfDocument.FromFile("document.pdf");
// Extract all text with one line
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);
using IronPdf;
// Load any PDF document
var pdf = PdfDocument.FromFile("document.pdf");
// Extract all text with one line
string allText = pdf.ExtractAllText();
Console.WriteLine(allText);
Imports IronPdf

' Load any PDF document
Dim pdf = PdfDocument.FromFile("document.pdf")
' Extract all text with one line
Dim allText As String = pdf.ExtractAllText()
Console.WriteLine(allText)
$vbLabelText   $csharpLabel

這段程式碼會載入 PDF 檔案並擷取其中的所有文字。 IronPDF 可以自動處理複雜的 PDF 結構、表單資料和編碼,而這些通常會為其他庫帶來問題。 從 PDF 文件中擷取的資料可儲存至文字檔,或進行後續處理以供分析。

實用技巧:您可以將提取的文字儲存到 .txt 檔案中以便稍後處理,或者解析它以填充資料庫、Excel 表格或知識庫。 這種方法適用於報告、合約或任何只需要快速取得原始文字的 PDF 檔案。 若需處理更複雜的資料擷取情境,請參閱完整的解析指南

如何從特定的 PDF 頁面中擷取資料?

為何要針對特定頁面進行抓取,而非提取所有內容?

實際應用中往往需要精確的資料擷取。 IronPDF 提供多種方法,可針對特定頁面中的重要資訊進行擷取。 在這個例子中,我們將使用以下PDF文件:

using IronPdf;
// Load PDF from a memory stream if needed
byte[] pdfBytes = File.ReadAllBytes("report.pdf");
var pdfFromStream = PdfDocument.FromBytes(pdfBytes);
// Or load from a URL
var pdfFromUrl = PdfDocument.FromUrl("___PROTECTED_URL_32___");
using IronPdf;
// Load PDF from a memory stream if needed
byte[] pdfBytes = File.ReadAllBytes("report.pdf");
var pdfFromStream = PdfDocument.FromBytes(pdfBytes);
// Or load from a URL
var pdfFromUrl = PdfDocument.FromUrl("___PROTECTED_URL_32___");
Imports IronPdf
' Load PDF from a memory stream if needed
Dim pdfBytes As Byte() = File.ReadAllBytes("report.pdf")
Dim pdfFromStream As PdfDocument = PdfDocument.FromBytes(pdfBytes)
' Or load from a URL
Dim pdfFromUrl As PdfDocument = PdfDocument.FromUrl("___PROTECTED_URL_32___")
$vbLabelText   $csharpLabel

如何在擷取的文字中搜尋關鍵資訊?

以下程式碼會從特定頁面擷取資料,並將結果輸出至主控台。 此技術在處理多頁 PDF 檔案,或需要將 PDF 分割以進行後續處理時,特別有用:

using IronPdf;
using System;
using System.Text.RegularExpressions;

// Load any PDF document
var pdf = PdfDocument.FromFile("AnnualReport2024.pdf");
// Extract from selected pages
int[] pagesToExtract = { 0, 2, 4 }; // Pages 1, 3, and 5
foreach (var pageIndex in pagesToExtract)
{
    string pageText = pdf.ExtractTextFromPage(pageIndex);
    // Split on 2 or more spaces (tables often flatten into space-separated values)
    var tokens = Regex.Split(pageText, @"\s{2,}");
    foreach (string token in tokens)
    {
        // Match totals, invoice headers, and invoice rows
        if (token.Contains("Invoice") || token.Contains("Total") || token.StartsWith("INV-"))
        {
            Console.WriteLine($"Important: {token.Trim()}");
        }
    }
}
using IronPdf;
using System;
using System.Text.RegularExpressions;

// Load any PDF document
var pdf = PdfDocument.FromFile("AnnualReport2024.pdf");
// Extract from selected pages
int[] pagesToExtract = { 0, 2, 4 }; // Pages 1, 3, and 5
foreach (var pageIndex in pagesToExtract)
{
    string pageText = pdf.ExtractTextFromPage(pageIndex);
    // Split on 2 or more spaces (tables often flatten into space-separated values)
    var tokens = Regex.Split(pageText, @"\s{2,}");
    foreach (string token in tokens)
    {
        // Match totals, invoice headers, and invoice rows
        if (token.Contains("Invoice") || token.Contains("Total") || token.StartsWith("INV-"))
        {
            Console.WriteLine($"Important: {token.Trim()}");
        }
    }
}
Imports IronPdf
Imports System
Imports System.Text.RegularExpressions

' Load any PDF document
Dim pdf = PdfDocument.FromFile("AnnualReport2024.pdf")
' Extract from selected pages
Dim pagesToExtract As Integer() = {0, 2, 4} ' Pages 1, 3, and 5
For Each pageIndex In pagesToExtract
    Dim pageText As String = pdf.ExtractTextFromPage(pageIndex)
    ' Split on 2 or more spaces (tables often flatten into space-separated values)
    Dim tokens = Regex.Split(pageText, "\s{2,}")
    For Each token As String In tokens
        ' Match totals, invoice headers, and invoice rows
        If token.Contains("Invoice") OrElse token.Contains("Total") OrElse token.StartsWith("INV-") Then
            Console.WriteLine($"Important: {token.Trim()}")
        End If
    Next
Next
$vbLabelText   $csharpLabel

此範例展示如何從 PDF 文件中擷取文字、搜尋關鍵資訊,並將其準備好以供儲存。 ExtractTextFromPage() 方法可保持文件的閱讀順序,使其非常適合文件分析和內容索引任務。 若需進行進階文字處理,您甚至可以對 PDF 文件中的文字進行搜尋與替換。

如何從 PDF 文件中擷取表格資料?

為何表格擷取與一般文字不同?

PDF 檔案中的表格沒有固定的結構; 它們只是排列成表格形狀的文字內容。 IronPDF 可以提取表格資料並保留佈局,以便您可以將其處理成 Excel 或文字檔案。 若遇到涉及 PDF 內圖片的較複雜情境,您可能需要將圖片另行擷取

如何將擷取的表格轉換為 CSV 格式?

using IronPdf;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

var pdf = PdfDocument.FromFile("example.pdf");
string rawText = pdf.ExtractAllText();
// Split into lines for processing
string[] lines = rawText.Split('\n');
var csvBuilder = new StringBuilder();
foreach (string line in lines)
{
    if (string.IsNullOrWhiteSpace(line) || line.Contains("Page"))
        continue;
    string[] rawCells = Regex.Split(line.Trim(), @"\s+");
    string[] cells;
    // If the line starts with "Product", combine first two tokens as product name
    if (rawCells[0].StartsWith("Product") && rawCells.Length >= 5)
    {
        cells = new string[rawCells.Length - 1];
        cells[0] = rawCells[0] + " " + rawCells[1]; // Combine Product + letter
        Array.Copy(rawCells, 2, cells, 1, rawCells.Length - 2);
    }
    else
    {
        cells = rawCells;
    }
    // Keep header or table rows
    bool isTableOrHeader = cells.Length >= 2
                           && (cells[0].StartsWith("Item") || cells[0].StartsWith("Product")
                               || Regex.IsMatch(cells[0], @"^INV-\d+"));
    if (isTableOrHeader)
    {
        Console.WriteLine($"Row: {string.Join("|", cells)}");
        string csvRow = string.Join(",", cells).Trim();
        csvBuilder.AppendLine(csvRow);
    }
}
// Save as CSV for Excel import
File.WriteAllText("extracted_table.csv", csvBuilder.ToString());
Console.WriteLine("Table data exported to CSV");
using IronPdf;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

var pdf = PdfDocument.FromFile("example.pdf");
string rawText = pdf.ExtractAllText();
// Split into lines for processing
string[] lines = rawText.Split('\n');
var csvBuilder = new StringBuilder();
foreach (string line in lines)
{
    if (string.IsNullOrWhiteSpace(line) || line.Contains("Page"))
        continue;
    string[] rawCells = Regex.Split(line.Trim(), @"\s+");
    string[] cells;
    // If the line starts with "Product", combine first two tokens as product name
    if (rawCells[0].StartsWith("Product") && rawCells.Length >= 5)
    {
        cells = new string[rawCells.Length - 1];
        cells[0] = rawCells[0] + " " + rawCells[1]; // Combine Product + letter
        Array.Copy(rawCells, 2, cells, 1, rawCells.Length - 2);
    }
    else
    {
        cells = rawCells;
    }
    // Keep header or table rows
    bool isTableOrHeader = cells.Length >= 2
                           && (cells[0].StartsWith("Item") || cells[0].StartsWith("Product")
                               || Regex.IsMatch(cells[0], @"^INV-\d+"));
    if (isTableOrHeader)
    {
        Console.WriteLine($"Row: {string.Join("|", cells)}");
        string csvRow = string.Join(",", cells).Trim();
        csvBuilder.AppendLine(csvRow);
    }
}
// Save as CSV for Excel import
File.WriteAllText("extracted_table.csv", csvBuilder.ToString());
Console.WriteLine("Table data exported to CSV");
Imports IronPdf
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.IO

Dim pdf = PdfDocument.FromFile("example.pdf")
Dim rawText As String = pdf.ExtractAllText()
' Split into lines for processing
Dim lines() As String = rawText.Split(ControlChars.Lf)
Dim csvBuilder As New StringBuilder()
For Each line As String In lines
    If String.IsNullOrWhiteSpace(line) OrElse line.Contains("Page") Then
        Continue For
    End If
    Dim rawCells() As String = Regex.Split(line.Trim(), "\s+")
    Dim cells() As String
    ' If the line starts with "Product", combine first two tokens as product name
    If rawCells(0).StartsWith("Product") AndAlso rawCells.Length >= 5 Then
        cells = New String(rawCells.Length - 2) {}
        cells(0) = rawCells(0) & " " & rawCells(1) ' Combine Product + letter
        Array.Copy(rawCells, 2, cells, 1, rawCells.Length - 2)
    Else
        cells = rawCells
    End If
    ' Keep header or table rows
    Dim isTableOrHeader As Boolean = cells.Length >= 2 AndAlso (cells(0).StartsWith("Item") OrElse cells(0).StartsWith("Product") OrElse Regex.IsMatch(cells(0), "^INV-\d+"))
    If isTableOrHeader Then
        Console.WriteLine($"Row: {String.Join("|", cells)}")
        Dim csvRow As String = String.Join(",", cells).Trim()
        csvBuilder.AppendLine(csvRow)
    End If
Next
' Save as CSV for Excel import
File.WriteAllText("extracted_table.csv", csvBuilder.ToString())
Console.WriteLine("Table data exported to CSV")
$vbLabelText   $csharpLabel

擷取複雜表格時常見哪些問題?

PDF 檔案中的表格通常只是排列成網格狀的文字。 此檢查有助於確定一行是屬於表格行還是表格標題。 透過過濾頁首、頁尾及無關文字,您可以從 PDF 中擷取乾淨的表格資料,並可直接匯出為 CSV 或 Excel 格式。

此工作流程適用於 PDF 表單、財務文件及報告。 您稍後可將擷取的資料轉換為 xlsx 檔案,或將其合併至 ZIP 檔案中。對於包含合併儲存格的複雜表格,您可能需要根據欄位位置調整解析邏輯。 處理掃描 PDF 檔案時,建議先使用 IronOCR 進行文字辨識。

Excel 試算表,顯示已擷取的產品資料,包含產品 A、B 和 C 的項目、數量、價格及總計欄位。 成功從 PDF 檔案中擷取表格資料,顯示包含數量、價格及計算總額的產品資訊。

如何從 PDF 檔案中擷取表單欄位資料?

為何要透過程式碼提取並修改表單欄位?

IronPDF 亦支援表單欄位資料的擷取與修改。 這在處理需要自動處理的可填寫 PDF 表單時特別有用:

using IronPdf;
using System.Drawing;
using System.Linq;

var pdf = PdfDocument.FromFile("form_document.pdf");
// Extract form field data
var form = pdf.Form;
foreach (var field in form) // Removed '.Fields' as 'FormFieldCollection' is enumerable
{
    Console.WriteLine($"{field.Name}: {field.Value}");
    // Update form values if needed
    if (field.Name == "customer_name")
    {
        field.Value = "Updated Value";
    }
}
// Save modified form
pdf.SaveAs("updated_form.pdf");
using IronPdf;
using System.Drawing;
using System.Linq;

var pdf = PdfDocument.FromFile("form_document.pdf");
// Extract form field data
var form = pdf.Form;
foreach (var field in form) // Removed '.Fields' as 'FormFieldCollection' is enumerable
{
    Console.WriteLine($"{field.Name}: {field.Value}");
    // Update form values if needed
    if (field.Name == "customer_name")
    {
        field.Value = "Updated Value";
    }
}
// Save modified form
pdf.SaveAs("updated_form.pdf");
Imports IronPdf
Imports System.Drawing
Imports System.Linq

Dim pdf = PdfDocument.FromFile("form_document.pdf")
' Extract form field data
Dim form = pdf.Form
For Each field In form ' Removed '.Fields' as 'FormFieldCollection' is enumerable
    Console.WriteLine($"{field.Name}: {field.Value}")
    ' Update form values if needed
    If field.Name = "customer_name" Then
        field.Value = "Updated Value"
    End If
Next
' Save modified form
pdf.SaveAs("updated_form.pdf")
$vbLabelText   $csharpLabel

若需進行更進階的表單處理,您亦可針對特定欄位類型進行操作:

// Work with different form field types
foreach (var field in pdf.Form)
{
    switch (field)
    {
        case TextFormField textField:
            Console.WriteLine($"Text field '{field.Name}': {textField.Value}");
            break;
        case CheckBoxFormField checkBox:
            Console.WriteLine($"Checkbox '{field.Name}': {checkBox.Value}");
            checkBox.Value = true; // Check the box
            break;
        case ComboBoxFormField comboBox:
            Console.WriteLine($"ComboBox '{field.Name}': {comboBox.Value}");
            // Set to first available option
            if (comboBox.Choices.Any())
                comboBox.Value = comboBox.Choices.First();
            break;
    }
}
// Work with different form field types
foreach (var field in pdf.Form)
{
    switch (field)
    {
        case TextFormField textField:
            Console.WriteLine($"Text field '{field.Name}': {textField.Value}");
            break;
        case CheckBoxFormField checkBox:
            Console.WriteLine($"Checkbox '{field.Name}': {checkBox.Value}");
            checkBox.Value = true; // Check the box
            break;
        case ComboBoxFormField comboBox:
            Console.WriteLine($"ComboBox '{field.Name}': {comboBox.Value}");
            // Set to first available option
            if (comboBox.Choices.Any())
                comboBox.Value = comboBox.Choices.First();
            break;
    }
}
' Work with different form field types
For Each field In pdf.Form
    Select Case field
        Case textField As TextFormField
            Console.WriteLine($"Text field '{field.Name}': {textField.Value}")
        Case checkBox As CheckBoxFormField
            Console.WriteLine($"Checkbox '{field.Name}': {checkBox.Value}")
            checkBox.Value = True ' Check the box
        Case comboBox As ComboBoxFormField
            Console.WriteLine($"ComboBox '{field.Name}': {comboBox.Value}")
            ' Set to first available option
            If comboBox.Choices.Any() Then
                comboBox.Value = comboBox.Choices.First()
            End If
    End Select
Next
$vbLabelText   $csharpLabel

何時該使用表單欄位擷取功能?

此程式碼片段從 PDF 中提取表單欄位值,並允許您以程式設計方式更新它們。 這使得處理 PDF 表單並提取特定資訊以供分析或生成報告變得輕而易舉。 這對於自動化工作流程非常有用,例如客戶註冊、調查處理或資料驗證。

常見的使用案例包括

  • 數位簽章自動化
  • 處理受密碼保護的 PDF 檔案
  • 擷取符合 PDF/A 標準的資料
  • 建立自訂工作流程

兩份 PDF 表單的並排比較——左側為包含範例資料(John Doe)的原始表單,右側為包含新資料(Updated Value)的更新後表單,展示 .NET 中的資料擷取與修改功能。 展示使用 .NET 成功擷取並修改 PDF 表單資料的對比圖,畫面底部可見 Visual Studio 除錯主控台顯示已擷取的客戶資訊。

接下來我該怎麼做?

IronPDF 讓 .NET 中的 PDF 資料擷取實用且有效率。 您可以從各種 PDF 文件中擷取文字、表格、表單欄位、圖片及附件,包括通常需要額外 OCR 處理的掃描 PDF 文件。

無論您的目標是建立知識庫、自動化報告工作流程,還是從財務 PDF 中提取資料,該庫都能為您提供完成此目標所需的工具,而無需手動複製或容易出錯的解析。 它操作簡便、速度快,並能直接整合至 Visual Studio 專案中。 試試看; 您將能節省大量時間,並避免處理 PDF 時常見的困擾。

若需處理更進階的應用情境,請參考:

!{--01001100010010010100001001010010010000010101001001011001010 111110100011101000101010101010001011111010100110101010001000001 010100100101010001000101010001000101111101010111010010010101010 001001000010111110101000001010101000010010000101111101010000010 1001001001111010001000101010101000011010101010001011111010101000101001001001001010101010001010010010010010100001010101010101 010101011000010101000100010101001110010001000101010001000101111101000010010011000100111110100010010011000100111100

準備好在您的應用程式中實現 PDF 資料提取功能了嗎? IronPDF 聽起來像您理想的 .NET 程式庫嗎? 立即開始免費試用,可用於商業用途。 請參閱我們的文件,以獲取完整的指南與 API 參考資料

常見問題解答

使用 .NET 從 PDF 文檔中提取文本的最佳方法是什麼?

使用 IronPDF,您可以輕鬆地在 .NET 應用程序中從 PDF 文檔中提取文本。它提供了高效檢索文本數據的方法,確保您可以訪問所需內容。

IronPDF 能處理掃描的 PDF 以進行數據提取嗎?

是的,IronPDF 支持 OCR(光學字符識別)以處理和提取掃描 PDF 中的數據,使您可以訪問圖像型文件中的文本。

如何使用 C# 從 PDF 中提取表格?

IronPDF 提供功能以在 C# 中解析和提取 PDF 文檔中的表格。您可以使用特定方法準確識別和檢索表格數據。

使用 IronPDF 進行 PDF 數據提取的好處是什麼?

IronPDF 提供了一整套 PDF 數據提取解決方案,包括文本檢索、表格解析和掃描文檔的 OCR。它能無縫整合至 .NET 應用程序,提供可靠且高效的方式來處理 PDF 數據。

使用 IronPDF 是否可以從 PDF 中提取圖像?

是的,IronPDF 允許從 PDF 文件中提取圖像。如果您需要訪問和操作嵌入在 PDF 文檔中的圖像,這個功能非常有用。

在數據提取期間,IronPDF 如何處理複雜的 PDF 佈局?

IronPDF 設計用於管理複雜的 PDF 佈局,提供強大的工具來瀏覽和提取數據,確保您可以處理具有復雜格式和結構的文檔。

我可以在 .NET 應用程序中自動化 PDF 數據提取嗎?

當然可以。IronPDF 可以集成到 .NET 應用程序中自動化 PDF 數據提取,簡化需要定期和一致數據檢索的流程。

我可以使用哪些編程語言與 IronPDF 進行 PDF 數據提取?

IronPDF 主要與 C# 一起使用於 .NET Framework,為希望以編程方式從 PDF 中提取數據的開發者提供廣泛的支持和功能。

IronPDF 是否支持提取 PDF 文檔的元數據?

是的,IronPDF 可以提取 PDF 文檔的元數據,允許您訪問作者、創建日期和其他文檔屬性等信息。

有哪些範例代碼可供學習使用 IronPDF 進行 PDF 數據提取?

開發人員指南提供了完整的 C# 教程及工作代碼範例,幫助您在 .NET 應用程序中掌握使用 IronPDF 進行 PDF 數據提取。

IronPDF是否完全相容於新的.NET 10版本,這對數據提取有什麼好處?

是的—IronPDF完全相容於.NET 10,支持其所有性能、API和執行環境改進,如減少堆積分配、數組介面去虛擬化和加強語言功能。這些改進使C#應用程式中的PDF數據提取工作流程更快、更有效率。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我