跳過到頁腳內容
使用 IRONOCR

C# 讀取 PDF 表單欄位:以程式設計方式擷取表單數據

對於開發人員來說,處理 PDF 表單可能是一件非常令人頭痛的事情。 無論你是處理求職申請、調查回應還是保險索賠,手動複製表單資料都非常耗時且容易出錯。 使用IronPDF ,您可以跳過所有繁瑣的工作,只需幾行程式碼即可從 PDF 文件中的互動式表單欄位中提取欄位值。 它將原本需要幾個小時才能完成的工作縮短到了幾秒鐘。

在本文中,我將向您展示如何使用 C# 中的表單物件來取得簡單表單中的所有欄位。 範例程式碼示範如何遍歷每個欄位並輕鬆提取其值。 它非常簡單易用,您無需費力地使用複雜的 PDF 檢視器,也無需處理隱藏的格式問題。

開始使用 IronPdf

設定 IronPDF 以提取 PDF 表單欄位只需極少的配置。 透過 NuGet 套件管理器安裝庫:

Install-Package IronPDF

或透過 Visual Studio 的套件管理器 UI。 IronPDF 支援 Windows、Linux、macOS 和Docker 容器,使其能夠靈活應用於各種部署場景。 有關詳細的設定說明,請參閱IronPDF 文件

使用 IronPDF 讀取 PDF 表單數據

以下程式碼顯示如何使用 IronPDF 讀取現有 PDF 文件中的所有欄位:

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Load the PDF document containing interactive form fields
        PdfDocument pdf = PdfDocument.FromFile("application_form.pdf");
        // Access the form object and iterate through all fields
        var form = pdf.Form;
        foreach (var field in form)
        {
            Console.WriteLine($"Field Name: {field.Name}");
            Console.WriteLine($"Field Value: {field.Value}");
            Console.WriteLine($"Field Type: {field.GetType().Name}");
            Console.WriteLine("---");
        }
    }
}
using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Load the PDF document containing interactive form fields
        PdfDocument pdf = PdfDocument.FromFile("application_form.pdf");
        // Access the form object and iterate through all fields
        var form = pdf.Form;
        foreach (var field in form)
        {
            Console.WriteLine($"Field Name: {field.Name}");
            Console.WriteLine($"Field Value: {field.Value}");
            Console.WriteLine($"Field Type: {field.GetType().Name}");
            Console.WriteLine("---");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

這段程式碼載入一個包含簡單表單的 PDF 文件,遍歷每個表單字段,並列印字段名稱、字段值和字段類型。 PdfDocument.FromFile()方法解析 PDF 文檔,而Form屬性提供對所有互動式表單欄位的存取。 每個欄位都暴露出其欄位類型特有的其他屬性,從而可以精確地提取資料。 對於更複雜的場景,請查閱IronPDF API 參考文檔,以了解高級表單操作方法。

輸出

C# 讀取 PDF 表單欄位:以程式設計方式擷取表單資料:圖 1 - 讀取 PDF 文件中所有表單欄位值的輸出結果

解讀不同的表單欄位類型

PDF 表單包含多種欄位類型,每種類型都需要特定的處理方式。 IronPDF 可自動識別欄位類型並提供客製化存取權限:

using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("complex_form.pdf");
// Text fields - standard input boxes
var nameField = pdf.Form.FindFormField("fullName");
string userName = nameField.Value;
// Checkboxes - binary selections
var agreeCheckbox = pdf.Form.FindFormField("termsAccepted");
bool isChecked = agreeCheckbox.Value == "Yes";
// Radio buttons - single choice from group
var genderRadio = pdf.Form.FindFormField("gender");
string selectedGender = genderRadio.Value;
// Dropdown lists (ComboBox) - predefined options
var countryDropdown = pdf.Form.FindFormField("country");
string selectedCountry = countryDropdown.Value;
// Access all available options
var availableCountries = countryDropdown.Choices;
// Multi-line text areas
var commentsField = pdf.Form.FindFormField("comments_part1_513");
string userComments = commentsField.Value;
// Grab all fields that start with "interests_"
var interestFields = pdf.Form
    .Where(f => f.Name.StartsWith("interests_"));
// Collect checked interests
List<string> selectedInterests = new List<string>();
foreach (var field in interestFields)
{
    if (field.Value == "Yes")  // checkboxes are "Yes" if checked
    {
        // Extract the interest name from the field name
        string interestName = field.Name.Replace("interests_", "");
        selectedInterests.Add(interestName);
    }
}
using IronPdf;
PdfDocument pdf = PdfDocument.FromFile("complex_form.pdf");
// Text fields - standard input boxes
var nameField = pdf.Form.FindFormField("fullName");
string userName = nameField.Value;
// Checkboxes - binary selections
var agreeCheckbox = pdf.Form.FindFormField("termsAccepted");
bool isChecked = agreeCheckbox.Value == "Yes";
// Radio buttons - single choice from group
var genderRadio = pdf.Form.FindFormField("gender");
string selectedGender = genderRadio.Value;
// Dropdown lists (ComboBox) - predefined options
var countryDropdown = pdf.Form.FindFormField("country");
string selectedCountry = countryDropdown.Value;
// Access all available options
var availableCountries = countryDropdown.Choices;
// Multi-line text areas
var commentsField = pdf.Form.FindFormField("comments_part1_513");
string userComments = commentsField.Value;
// Grab all fields that start with "interests_"
var interestFields = pdf.Form
    .Where(f => f.Name.StartsWith("interests_"));
// Collect checked interests
List<string> selectedInterests = new List<string>();
foreach (var field in interestFields)
{
    if (field.Value == "Yes")  // checkboxes are "Yes" if checked
    {
        // Extract the interest name from the field name
        string interestName = field.Name.Replace("interests_", "");
        selectedInterests.Add(interestName);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

FindFormField()方法允許按名稱直接存取特定字段,無需遍歷所有表單字段。 複選框選中時返回"是",單選按鈕返回所選值。 選擇欄位(例如下拉式清單和列錶框)透過Choices屬性提供欄位值和所有可用選項。 這套全面的方法使開發人員能夠存取和提取複雜互動式表單中的資料。 處理複雜表單時,請考慮使用IronPDF 的表單編輯功能,在以程式設計方式擷取之前填寫或修改欄位值。

在這裡,您可以看到 IronPDF 如何處理更複雜的表單,並從表單欄位值中提取資料:

C# 讀取 PDF 表單欄位:以程式方式擷取表單資料:圖 2 - 複雜表單讀取輸出

真實案例:處理調查表

設想這樣一個場景:你需要處理數百份來自客戶調查的 PDF 表格。 以下程式碼示範如何使用 IronPDF 進行批次處理:


using IronPdf;
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;

public class SurveyProcessor
{
    static void Main(string[] args)
    {
        ProcessSurveyBatch(@"C:\Surveys");
    }

    public static void ProcessSurveyBatch(string folderPath)
    {
        StringBuilder csvData = new StringBuilder();
        csvData.AppendLine("Date,Name,Email,Rating,Feedback");
        foreach (string pdfFile in Directory.GetFiles(folderPath, "*.pdf"))
        {
            try
            {
                PdfDocument survey = PdfDocument.FromFile(pdfFile);
                string date = survey.Form.FindFormField("surveyDate")?.Value ?? "";
                string name = survey.Form.FindFormField("customerName")?.Value ?? "";
                string email = survey.Form.FindFormField("email")?.Value ?? "";
                string rating = survey.Form.FindFormField("satisfaction")?.Value ?? "";
                string feedback = survey.Form.FindFormField("comments")?.Value ?? "";
                feedback = feedback.Replace("\n", " ").Replace("\"", "\"\"");
                csvData.AppendLine($"{date},{name},{email},{rating},\"{feedback}\"");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}");
            }

using IronPdf;
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;

public class SurveyProcessor
{
    static void Main(string[] args)
    {
        ProcessSurveyBatch(@"C:\Surveys");
    }

    public static void ProcessSurveyBatch(string folderPath)
    {
        StringBuilder csvData = new StringBuilder();
        csvData.AppendLine("Date,Name,Email,Rating,Feedback");
        foreach (string pdfFile in Directory.GetFiles(folderPath, "*.pdf"))
        {
            try
            {
                PdfDocument survey = PdfDocument.FromFile(pdfFile);
                string date = survey.Form.FindFormField("surveyDate")?.Value ?? "";
                string name = survey.Form.FindFormField("customerName")?.Value ?? "";
                string email = survey.Form.FindFormField("email")?.Value ?? "";
                string rating = survey.Form.FindFormField("satisfaction")?.Value ?? "";
                string feedback = survey.Form.FindFormField("comments")?.Value ?? "";
                feedback = feedback.Replace("\n", " ").Replace("\"", "\"\"");
                csvData.AppendLine($"{date},{name},{email},{rating},\"{feedback}\"");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}");
            }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

常見問題解答

IronPDF 如何協助在 C# 中讀取 PDF 表單欄位?

IronPDF 提供了一個簡化的流程,可以從 C# 中的可填寫 PDF 中提取表單欄位數據,與手動資料擷取相比,大幅減少了所需的時間和精力。

IronPDF 可以擷取哪些類型的 PDF 表單欄位?

使用 IronPDF,您可以從可填寫 PDF 中提取各種表單字段,包括文字輸入框、複選框、下拉選擇框等等。

自動擷取PDF表單資料有何好處?

使用 IronPDF 自動擷取 PDF 表單資料可以節省時間、減少錯誤,並透過消除手動資料輸入來提高生產力。

IronPDF 是否適合處理大量的 PDF 表單?

是的,IronPDF 旨在有效處理大量 PDF 表單,因此非常適合處理求職申請、調查和其他大量文件任務。

與手動輸入資料相比,使用 IronPDF 有哪些優勢?

IronPDF 可以減少人為錯誤,加速資料擷取流程,並讓開發人員專注於更複雜的任務,而不是枯燥的資料輸入。

IronPDF 可以處理不同的 PDF 格式嗎?

IronPDF能夠處理各種PDF格式,確保其多功能性,並與各種文件和表單設計相容。

IronPDF 如何提高資料擷取的準確性?

IronPDF 透過自動化提取過程,最大限度地降低了手動資料輸入過程中經常出現的人為錯誤風險,從而提高了準確性。

IronPDF 使用什麼程式語言?

IronPDF 旨在與 C# 一起使用,為開發人員提供強大的工具,以便在 .NET 應用程式中操作 PDF 文件和提取資料。

Kannaopat Udonpant
軟體工程師
在成為软件工程師之前,Kannapat 從日本北海道大學完成了環境資源博士學位。在追逐學位期间,Kannapat 還成為了生產工程系一部份——汽車机器人实验室的成員。2022 年,他利用他的 C# 技能加入 Iron Software 的工程團隊, 專注於 IronPDF。Kannapat 珍惜他的工作,因为他直接向编写大部分 IronPDF 使用的代码的开发者学习。除了同行学习,Kannapat 还喜欢在 Iron Software 工作的社交十环。当他不编写代码或文档时,Kannapat 通常在他的 PS5 上打游戏或重看《The Last of Us》。