iText7是否仅支持C#?能否在VB.NET中用其提取PDF文本字段?
VB Winform提取PDF文本字段内容最优方案
首先明确:iText7仅面向C#是认知误区,它基于.NET Standard实现,可无缝在VB.NET项目中调用,C#的相关示例仅需简单语法转换即可在VB中使用。
方案1:使用iText7实现(功能最完善,推荐非商用场景使用)
注意:iText7采用AGPL协议,若你的项目为闭源商用,需要购买官方商业授权
- 安装依赖:通过NuGet搜索并安装
iText7、iText7.Forms两个包 - 功能实现代码示例:
Imports iText.Kernel.Pdf Imports iText.Forms Imports System.Collections.Generic Public Sub ExtractPdfFormFields(pdfPath As String) ' 存储提取到的字段键值对 Dim fieldDict As New Dictionary(Of String, String)() ' 加载PDF文件,Using块自动释放资源 Using pdfReader As New PdfReader(pdfPath) Using pdfDoc As New PdfDocument(pdfReader) ' 获取AcroForm表单对象 Dim acroForm As PdfAcroForm = PdfAcroForm.GetAcroForm(pdfDoc, True) If acroForm Is Nothing Then Exit Sub ' 遍历所有文本字段 For Each fieldItem In acroForm.GetFormFields() Dim fieldName = fieldItem.Key Dim fieldValue = fieldItem.Value.GetValueAsString() fieldDict.Add(fieldName, fieldValue) ' 此处可添加自定义逻辑,比如将字段值绑定到Winform控件 Next End Using End Using End Sub
如果需要处理加密PDF,仅需在初始化PdfReader时传入密码参数即可。
方案2:使用iTextSharp 5.x实现(适合闭源商用场景)
iTextSharp是iText的旧版,已停止维护但功能稳定,采用LGPL协议,闭源商用无需购买授权,原生支持VB.NET开发。
- 安装依赖:通过NuGet搜索并安装
iTextSharp最新5.x版本 - 功能实现代码示例:
Imports iTextSharp.text.pdf Imports System.Collections.Generic Public Sub ExtractPdfFormFieldsOld(pdfPath As String) Dim fieldDict As New Dictionary(Of String, String)() Using pdfReader As New PdfReader(pdfPath) Dim acroFields As AcroFields = pdfReader.AcroFields If acroFields Is Nothing Then Exit Sub For Each fieldName As String In acroFields.Fields.Keys Dim fieldValue = acroFields.GetField(fieldName) fieldDict.Add(fieldName, fieldValue) Next End Using End Sub
补充说明
- 两种方案均无需额外依赖,可直接在Winforms项目中运行
- 所有公开的C#版iText7示例,均可通过语法转换工具快速转成VB可用代码,功能无任何差异
- 若遇到无法识别的表单字段,可优先检查PDF是否为动态XFA表单,两种方案默认仅支持标准AcroForm表单提取,XFA表单需额外开启对应参数。
内容的提问来源于stack exchange,提问作者Hugh Self Taught
相关产品推荐
相关产品推荐

