使用IRONPDF

C# 教程:使用 IronPDF 构建 PDF 文本内容查看器(Windows 窗体)

在当今的数字时代,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 文件。

Windows Windows 安装程序
使用 IronPDF Windows Installer 直接安装产品。

构建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 窗体应用程序 (.NET Framework)”或类似的 .NET 模板。

Visual Studio 新项目对话框

Visual Studio 新建项目创建

接下来,为您的项目提供一个名称(例如,CSharpPdfTextReader),然后点击“创建”按钮。 这将设置一个新的 Windows Forms 应用程序项目。

第 2 步:安装 IronPDF 库

使用 NuGet 包管理器 GUI

  1. 在解决方案资源管理器中,右键单击您的项目并选择“管理 NuGet 包...”

  2. 转到“浏览”选项卡,然后搜索“IronPdf”。

  3. 选择IronPdf软件包并点击“安装”。

    在 Visual Studio 中的 NuGet 包管理器搜索 IronPDF

    通过NuGet包管理器安装IronPDF

    --LIBRARY_NUGET_INSTALL_BLOCK--

使用 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

    将 RichTextBox 添加到 Form1 以显示提取的 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" 或点击 "Start" 按钮运行应用程序。

    您的应用程序窗口将出现。 点击“打开 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表单

请记住,本教程专注于一个特定的用例:在C#应用程序中使PDF文本可访问。 您可以在此基础上进行调整和扩展,以满足更复杂的需求。

如果您有兴趣探索IronPDF的全部潜力:

  • 查阅IronPDF 文档,获取详细的指南和示例。
  • 要在生产应用程序中使用IronPDF而不受试用限制,需要许可证密钥。 您可以从 IronPDF 网站购买许可证。 许可证起价为$749。
  • 您也可以通过免费试用评估完整的商业版本。

    LIBRARY_GET_STARTED_WITH_PRODUCT_TRIAL_EXTENDED_BLOCK

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
如何在C#中读取PDF表格
下一步 >
如何在 C# 中将 Word (Docx) 转换为 PDF(教程)