使用 IRONPDF

C# 教程:使用 IronPDF 建立 PDF 文本內容檢視器(Windows Forms)

在當今的數位時代,PDF 文件已成為教育、商務和個人使用中許多工作流程的核心。 它們是一種用於分享和展示多樣數據的標準格式,包括文本、圖像和表格。

在 C# Windows Forms 應用程式中顯示具完整視覺保真度的完整 PDF 文件可能需要專用的渲染元件,但開發人員通常會有其他需求。 有時候,目標是使用 C# 讀取 PDF 文本,提取數據,或顯示 PDF 的文本內容以便快速查看、編索引或提高可訪問性。

本文將指導您創建一個專注於此特定任務的應用程式:使用IronPDF這個強大的.NET庫來構建一個簡單的C# PDF文本查看器。 您將學習如何使用IronPDF在Windows Forms應用程式中載入PDF並有效地提取和顯示其文本內容。

什麼是 IronPDF?

IronPDF 是一個功能全面的 C# 庫,使 .NET 開發者能夠在其應用程式中建立、編輯和處理 PDF 檔案。 它允許使用者將 HTML、圖片和 SVG 轉換為 PDF 文件,對於本教程而言,還可以讀取和提取現有 PDF 內容。 IronPDF 設計為易於使用,並提供廣泛的功能來操作 PDF 文件。

!!!

建立 PDF 文本查看器的要求

要建立此 C# PDF 文字顯示應用程式,您將需要:

  • Visual Studio:一個用於創建 Windows Forms 應用程序的集成開發環境 (IDE)。
  • IronPDF:一個 NuGet 套件,提供讀取、創建和操作 PDF 文件的功能,包括文字提取。

    展示將HTML轉換為PDF概念的插圖

    IronPDF 還可以從 HTML 創建 PDF,這是本教程中顯示的文本提取功能之外的另一個功能。

使用IronPDF在C#中創建PDF文本內容檢視器的步驟

步驟 1:在 Visual Studio 中建立新的 Windows Forms 應用程式

首先,啟動 Visual Studio,然後點擊「建立新專案」。 從清單中選擇「Windows Forms App (.NET Framework)」或類似的 .NET 範本。

Visual Studio 新專案對話框

Visual Studio 新專案建立

接下來,為您的專案提供一個名稱(例如,CSharpPdfTextReader),然後點擊建立按鈕。 這將建立一個新的 Windows Forms 應用程式專案。

步驟 2:安裝 IronPDF 函式庫

使用 NuGet 套件管理器 GUI

  1. 在方案總管中,右擊您的專案並選擇「管理 NuGet 套件...」

  2. 前往「瀏覽」標籤,然後搜尋「IronPdf」。

  3. 選擇IronPdf套件並點擊“Install”。

    Visual Studio 中的 NuGet 套件管理員正在搜索 IronPDF

    通過 NuGet 套件管理器安裝 IronPDF

    NuGet 使用NuGet安裝

    PM >  Install-Package IronPdf

    NuGet上查看https://www.nuget.org/packages/IronPdf以獲取快速安裝。已超過1000萬次下載,正用C#改變PDF開發。 您也可以下載DLLWindows 安裝程式

使用 NuGet 套件管理器控制台

或者,開啟套件管理器主控台(工具 > NuGet 套件管理員 > 套件管理器主控台),然後執行命令:

Install-Package IronPdf
Install-Package IronPdf
SHELL

這將下載並安裝IronPDF及其相依項目到您的專案中。

步驟 3:在您的表單中添加一個 RichTextBox 用於顯示文本

我們將使用RichTextBox控制項來顯示從 PDF 提取的文本內容。 RichTextBox 適合顯示格式化文本,但在本教程中,其主要角色是呈現由 IronPDF 提取的純文本。 它有效地顯示文本信息,而不嘗試呈現 PDF 的原始視覺布局。

若要新增RichTextBox

  1. 在設計視圖中打開您的表單。

  2. 前往工具箱(檢視 > 工具箱)。

  3. 在 "Common Controls" 下找到 RichTextBox,然後拖到表單上。

  4. 根據需要調整其大小和位置。 在屬性視窗中,您可以設置其Name(例如,pdfDataRichTextBox)並將其Dock屬性設置為Fill,如果您希望它佔據大部分表單。

    PDF 檢視器 C# Windows 應用程式(教程),圖 4:在 Form1 中訪問 RickTextBox

    在 Form1 中添加 RichTextBox 以顯示提取的 PDF 文本

步驟 4:添加按鈕以選擇 PDF 檔案

在表單中添加一個Button控制項。 用戶將點擊此按鈕以打開文件對話框並選擇一個 PDF 文件進行文本提取。

  1. 從工具箱將Button拖到您的表單上。

  2. 在屬性視窗中,設定其Name(例如:openBtn)和Text(例如:"Open PDF & Display Text")。

    PDF 檢視器 C# Windows 應用程式(教學),圖 5:新增一個按鈕到 Form1

    在 Form1 中添加按鈕以觸發 PDF 選擇

步驟 5:添加 C# 程式碼以載入 PDF 並提取文本

雙擊您剛剛添加的按鈕(“Open PDF & Display Text”)以在Form1.cs中創建其Click事件處理程序。

首先,請確保在Form1.cs文件的頂部匯入IronPDF命名空間:

using IronPdf;
using System; // For EventArgs, Exception
using System.Windows.Forms; // For OpenFileDialog, MessageBox, DialogResult, etc.
using IronPdf;
using System; // For EventArgs, Exception
using System.Windows.Forms; // For OpenFileDialog, MessageBox, DialogResult, etc.
Imports IronPdf
Imports System ' For EventArgs, Exception
Imports System.Windows.Forms ' For OpenFileDialog, MessageBox, DialogResult, etc.
$vbLabelText   $csharpLabel

現在,實作按鈕點擊事件的處理程式。 此程式碼將:

  1. 提示使用者選擇一個PDF檔案。

  2. 使用 IronPDF 加載所選的 PDF。

  3. 使用 IronPDF 的 ExtractAllText() 方法從 PDF 中獲取所有文本。

  4. RichTextBox中顯示此提取的文本。
private void openBtn_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    openFileDialog.Title = "Select a PDF file to extract text from";

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        try
        {
            // It's recommended to set your license key once at application startup.
            // License.LicenseKey = "YourIronPdfLicenseKey"; 
            // If no key is set, IronPDF runs in trial mode (watermarks on output, time limits).
            // For text extraction, the trial is fully functional for development.

            // Load the selected PDF using IronPDF
            var pdf = PdfDocument.FromFile(openFileDialog.FileName);

            // Extract all text content from the PDF
            string extractedText = pdf.ExtractAllText();

            // Display the extracted text in the RichTextBox
            // (Assuming your RichTextBox is named pdfDataRichTextBox, change if different)
            pdfDataRichTextBox.Text = extractedText; 
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while processing the PDF file: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
private void openBtn_Click(object sender, EventArgs e)
{
    var openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "PDF files (*.pdf)
*.pdf
All files (*.*)
*.*";
    openFileDialog.Title = "Select a PDF file to extract text from";

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        try
        {
            // It's recommended to set your license key once at application startup.
            // License.LicenseKey = "YourIronPdfLicenseKey"; 
            // If no key is set, IronPDF runs in trial mode (watermarks on output, time limits).
            // For text extraction, the trial is fully functional for development.

            // Load the selected PDF using IronPDF
            var pdf = PdfDocument.FromFile(openFileDialog.FileName);

            // Extract all text content from the PDF
            string extractedText = pdf.ExtractAllText();

            // Display the extracted text in the RichTextBox
            // (Assuming your RichTextBox is named pdfDataRichTextBox, change if different)
            pdfDataRichTextBox.Text = extractedText; 
        }
        catch (Exception ex)
        {
            MessageBox.Show("An error occurred while processing the PDF file: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
Private Sub openBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
	Dim openFileDialog As New OpenFileDialog()
	openFileDialog.Filter = "PDF files (*.pdf) *.pdf All files (*.*) *.*"
	openFileDialog.Title = "Select a PDF file to extract text from"

	If openFileDialog.ShowDialog() = DialogResult.OK Then
		Try
			' It's recommended to set your license key once at application startup.
			' License.LicenseKey = "YourIronPdfLicenseKey"; 
			' If no key is set, IronPDF runs in trial mode (watermarks on output, time limits).
			' For text extraction, the trial is fully functional for development.

			' Load the selected PDF using IronPDF
			Dim pdf = PdfDocument.FromFile(openFileDialog.FileName)

			' Extract all text content from the PDF
			Dim extractedText As String = pdf.ExtractAllText()

			' Display the extracted text in the RichTextBox
			' (Assuming your RichTextBox is named pdfDataRichTextBox, change if different)
			pdfDataRichTextBox.Text = extractedText
		Catch ex As Exception
			MessageBox.Show("An error occurred while processing the PDF file: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
		End Try
	End If
End Sub
$vbLabelText   $csharpLabel

程式碼解析:

  • openFileDialog:用於選擇檔案的標準對話框,篩選 PDF 檔案。
  • PdfDocument.FromFile(openFileDialog.FileName):此 IronPDF 方法將選定的 PDF 加載到 PdfDocument 對象中。
  • pdf.ExtractAllText():這是本教程中關鍵的 IronPDF 函數。 它會讀取整個 PDF,並將所有可識別的文字內容提取為單個字串。 這在 C# 解析 PDF 文本 的場景中是非常有用的。
  • pdfDataRichTextBox.Text = extractedText;: 然後將提取的文本賦值給您的RichTextBoxText屬性(確保名稱pdfDataRichTextBox與您給RichTextBox控件的名稱匹配)。

    這展示了IronPDF如何簡化在C#中读取PDF文本,使開發人員能夠以最少的精力以程式化方式訪問PDF內容。

步驟 6:構建並運行您的 C# PDF 文本查看器應用程式

  1. 在 Visual Studio 中,前往「建置」選單並選擇「建置方案」。

  2. 建置成功後,按下「F5」或點擊「開始」按鈕來執行應用程式。

    您的應用程式視窗將會出現。 點擊“打開 PDF 並顯示文本”按鈕,從您的電腦中選擇一個 PDF 文件,然後點擊“打開”。

    PDF 檢視器 C# Windows 應用程序(教程),圖 6:運行應用程序

    運行 C# PDF 文本查看應用程式

    RichTextBox 隨後將顯示從所選 PDF 檔案中提取的文字內容。

    PDF 檢視器 C# Windows 應用程式(教學),圖 7:選擇 PDF 文件後顯示的文字內容

    從 PDF 中提取的文本內容並顯示在 RichTextBox

    有關在 MAUI 應用程式中視覺化呈現 PDF 的資訊(這與本教程的文字提取重點不同),您可以探索「MAUI 教程中的 PDF 查看」。

結論:使用 C# 和 IronPDF 輕鬆訪問 PDF 文本內容

通過遵循這些步驟,您已經創建了一個 C# Windows Forms 應用程式,該應用程式使用 IronPDF 有效地提取和顯示 PDF 文件中的文本內容。 當您需要以編程方式存取PDF中的文字信息,用於顯示、分析或在您的.NET應用程式中進一步處理時,這種方法非常有價值。

IronPDF 提供強大的 C# PDF 文字提取功能,而這只是其全面功能集的一部分。 您也可以使用IronPDF執行更進階的任務,例如在PDF中搜索文本、編輯PDF表單

請記住,本教程專注於一個特定的使用案例:使 PDF 文本在 C# 應用程式中可訪問。 您可以調整和擴展這個基礎以滿足更複雜的需求。

如果您有興趣探索IronPDF的全部潛力:

  • 深入研究IronPDF 文件以獲取詳細指南和範例。
  • 在生產應用程式中使用IronPDF,若要不受試用限制,需要授權金鑰。 您可以從 IronPDF 網站 購買許可證。 授權價格從$749起。
  • 您也可以透過免費試用來評估完整的商業版本。

    現在開始使用IronPDF。
    green arrow pointer

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
如何在C#中讀取PDF表格
下一個 >
如何在C#中將Word(Docx)轉換為PDF(教程)