使用 VB.net 和 iTextSharp 删除 acroform 上字段的 MAXLEN 值

Use VB.net and iTextSharp to remove the MAXLEN value of a field on an acroform

我将 Visual Basic 与 iTextSharp 结合使用来填充 PDF 表单。

除了其中一个表单字段的长度太短之外,一切都很棒。

据我所知,我需要从字典中删除该字段的 MAXLEN 值...但如果我能找到如何使用 VB 和 iTextSharp 执行此操作,我会感到很困惑。

字段本身称为 "internalP",当前设置为 4 个字符的长度。我需要将它设置为 10 个字符。

我确实假设我可以以某种方式编辑该字段,但是花了几个小时环顾四周,我认为解决方案只是删除 MAXLEN 属性,只是我找不到任何示例代码。

有人可以帮忙吗?

目前我运行的代码是这样的:

你好,我的代码如下:

 Imports iTextSharp.text.pdf
 Imports iTextSharp.text
 Imports System.IO


 Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim pdfTemplate As String = "z:\shared\LP1F.pdf"
    Dim newFile As String = "z:\shared\Final.pdf"

    Dim pdfReader As New PdfReader(pdfTemplate)
    Dim pdfStamper As New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))

    Dim pdfFormFields As AcroFields = pdfStamper.AcroFields


    ' set form pdfFormFields
    '''
    'this was my first attempt but is not working
    'I receive a compilation error saying that I can't use nul'
    '''
     pdfFormFields.SetFieldProperty("internalP", "FieldMaxLength", 10, null)
     pdfFormFields.RegenerateField("internalP")
     pdfFormFields.SetField("internalP", "1234567890")


    '''
    ' therefore I started with this code, but then got stuck!!
    '''
    Dim item As AcroFields.Item
    item = pdfFormFields.GetFieldItem("internalP")
    Dim pdfDictionary As PdfDictionary = item.GetWidget(0)
    pdfDictionary.Remove(PdfName.MAXLEN)


    MessageBox.Show("Finished")

    ' flatten the form to remove editting options, set it to false
    ' to leave the form open to subsequent manual edits
    pdfStamper.FormFlattening = False

    ' close the pdf
    pdfStamper.Close()

End Sub

End Class

Bruno's answer here 让你深刻理解发生了什么,我真的推荐你读一读。但是,它适用于不同的 属性,因此下面的代码应该适合您。

''//Get the form item
Dim fi = pdfFormFields.GetFieldItem("internalP")

''//Get the merged propertoes
Dim props = fi.GetMerged(0)

''//Set a new value
props.Put(PdfName.MAXLEN, New PdfNumber(10))

我建议在其中进行一些 null 和绑定检查,但这应该能让你继续。