跳過到頁腳內容
使用IRONPDF

如何在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("---");
        }
    }
}
Imports IronPdf
Imports System

Class Program
    Shared Sub Main(args As String())
        ' Load the PDF document containing interactive form fields
        Dim pdf As PdfDocument = PdfDocument.FromFile("application_form.pdf")
        ' Access the form object and iterate through all fields
        Dim form = pdf.Form
        For Each field In form
            Console.WriteLine($"Field Name: {field.Name}")
            Console.WriteLine($"Field Value: {field.Value}")
            Console.WriteLine($"Field Type: {field.GetType().Name}")
            Console.WriteLine("---")
        Next
    End Sub
End Class
$vbLabelText   $csharpLabel

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

解讀不同的表單欄位類型

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);
    }
}
Imports IronPdf

Dim pdf As PdfDocument = PdfDocument.FromFile("complex_form.pdf")

' Text fields - standard input boxes
Dim nameField = pdf.Form.FindFormField("fullName")
Dim userName As String = nameField.Value

' Checkboxes - binary selections
Dim agreeCheckbox = pdf.Form.FindFormField("termsAccepted.")
Dim isChecked As Boolean = agreeCheckbox.Value = "Yes"

' Radio buttons - single choice from group
Dim genderRadio = pdf.Form.FindFormField("gender")
Dim selectedGender As String = genderRadio.Value

' Dropdown lists (ComboBox) - predefined options
Dim countryDropdown = pdf.Form.FindFormField("country")
Dim selectedCountry As String = countryDropdown.Value

' Access all available options
Dim availableCountries = countryDropdown.Choices

' Multi-line text areas
Dim commentsField = pdf.Form.FindFormField("comments_part1_513")
Dim userComments As String = commentsField.Value

' Grab all fields that start with "interests_"
Dim interestFields = pdf.Form.Where(Function(f) f.Name.StartsWith("interests_"))

' Collect checked interests
Dim selectedInterests As New List(Of String)()
For Each field In interestFields
    If field.Value = "Yes" Then ' checkboxes are "Yes" if checked
        ' Extract the interest name from the field name
        Dim interestName As String = field.Name.Replace("interests_", "")
        selectedInterests.Add(interestName)
    End If
Next
$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}");
            }
        }
        File.WriteAllText("survey_results.csv", csvData.ToString());
        Console.WriteLine("Survey processing complete!");
    }
}
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}");
            }
        }
        File.WriteAllText("survey_results.csv", csvData.ToString());
        Console.WriteLine("Survey processing complete!");
    }
}
Imports IronPdf
Imports System
Imports System.Text
Imports System.IO
Imports System.Collections.Generic

Public Class SurveyProcessor
    Shared Sub Main(args As String())
        ProcessSurveyBatch("C:\Surveys")
    End Sub

    Public Shared Sub ProcessSurveyBatch(folderPath As String)
        Dim csvData As New StringBuilder()
        csvData.AppendLine("Date,Name,Email,Rating,Feedback")

        For Each pdfFile As String In Directory.GetFiles(folderPath, "*.pdf")
            Try
                Dim survey As PdfDocument = PdfDocument.FromFile(pdfFile)
                Dim [date] As String = If(survey.Form.FindFormField("surveyDate")?.Value, "")
                Dim name As String = If(survey.Form.FindFormField("customerName")?.Value, "")
                Dim email As String = If(survey.Form.FindFormField("email")?.Value, "")
                Dim rating As String = If(survey.Form.FindFormField("satisfaction")?.Value, "")
                Dim feedback As String = If(survey.Form.FindFormField("comments")?.Value, "")
                feedback = feedback.Replace(vbLf, " ").Replace("""", """""")
                csvData.AppendLine($"{[date]},{name},{email},{rating},""{feedback}""")
            Catch ex As Exception
                Console.WriteLine($"Error processing {pdfFile}: {ex.Message}")
            End Try
        Next

        File.WriteAllText("survey_results.csv", csvData.ToString())
        Console.WriteLine("Survey processing complete!")
    End Sub
End Class
$vbLabelText   $csharpLabel

此方法處理指定資料夾中所有 PDF 文件中的互動式表單字段,提取調查回复,並將其編譯成 CSV 檔案。空值合併運算子 (??) 會為缺失欄位提供空字串,從而避免異常。 回饋文字已進行清理,以符合 CSV 格式,具體做法是轉義引號並刪除換行符。 錯誤處理機制確保單一損壞的檔案不會導致整個批次過程停止。

如何在 C# 中以程式設計方式讀取 PDF 表單欄位:圖 3 - 用於提取調查表單資料的 CSV 檔案輸出

應對常見挑戰

使用PDF表單時,請注意以下事項:

  • 受密碼保護的 PDF 檔案:PdfDocument.FromFile("secured.pdf", "password")。
  • PDF 表單欄位中缺少名稱或名稱相同:檢查 pdf.Form 集合中的空值檢查。
  • 扁平化表單:有時 PDF 表單資料會在 PDF 檢視器中呈現,在這種情況下,可能需要使用文字擷取方法,而不是讀取表單欄位。

使用 IronPDF,您可以建立簡單的表單,存取切換按鈕欄位、列錶框、單選按鈕和複選框,甚至可以以程式設計方式操作互動式表單欄位。 如需全面的錯誤處理策略,請參閱Microsoft 異常處理文件

結論

IronPDF 簡化了在 C# 中讀取 PDF 表單欄位的操作,提供了對各種欄位類型的直覺訪問,從複選框、單選按鈕、列錶框和切換按鈕欄位到文字欄位。 透過使用像上面 static void Main 程式碼片段這樣的範例程式碼,開發人員可以有效地從 PDF 表單中提取資料,將其整合到 Visual Studio 專案中,並自動執行文件工作流程,而無需依賴 Adobe Reader。

準備好從工作流程中徹底消除手動資料輸入了嗎? 首先可以免費試用,並根據您的需求進行擴充。

常見問題解答

如何使用 C# 從 PDF 表單欄位中提取數據?

您可以使用 IronPDF 在 C# 中從 PDF 表單欄位中提取數據。它允許您通過簡單的代碼範例來讀取可填寫 PDF 文件中的文本、複選框、下拉列表等。

IronPDF 可以處理哪些類型的表單欄位?

IronPDF 可以處理各種類型的表單欄位,包括文本欄位、複選框、單選按鈕、下拉列表等,使其在從可填寫的 PDF 中提取數據時非常靈活。

為什麼開發人員應該使用 IronPDF 來處理 PDF 表單?

開發人員應該使用 IronPDF 來處理 PDF 表單,因為它可以顯著減少提取表單數據所需的時間和精力,減少手動錯誤並提高效率。

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

是的,IronPDF 適合處理大量的 PDF 表單,因為它可以快速從互動式表單欄位提取欄位值,節省時間並減少出錯的可能性。

使用IronPDF是否有可用的代碼範例?

是的,IronPDF 提供簡單的代碼範例,幫助開發人員輕鬆地將 PDF 表單欄位提取整合到其 C# 項目中。

IronPDF 可以用於處理調查回應嗎?

是的,IronPDF 非常適合處理調查回應,因為它可以高效地讀取並從互動式 PDF 文件中的各種表單欄位中提取數據。

使用 IronPDF 提取 PDF 表單數據的好處是什麼?

使用 IronPDF 提取 PDF 表單數據的好處是可以自動化過程,令其比起手動數據輸入更快速且更不容易出錯。

IronPDF 如何改善 PDF 表單處理?

IronPDF 通過允許開發人員以程式化方式提取表單欄位數據,減少與手動方法相比所需的時間和精力來改善 PDF 表單處理。

IronPDF 支援互動式 PDF 表單欄位嗎?

是的,IronPDF 完全支援互動式 PDF 表單欄位,讓開發人員能夠輕鬆提取和操作應用程式中的表單數據。

IronPDF在讀取PDF表單欄位方面是否與.NET 10兼容?

是的 — IronPDF完全與.NET 10兼容,包括讀取、寫入和展平表單欄位。在.NET 10項目中使用IronPDF不需要特殊解決方案,讓您可以無縫加載包含表單的PDF通過`PdfDocument.FromFile(...)`,通過`pdf.Form`或`FindFormField(...)`訪問欄位,並像在早期版本中一樣檢索值。

Curtis Chau
技術作家

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

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

鋼鐵支援團隊

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