I'm working on a vb.net app to fill preexisting pdf forms and I've run in to a frustrating problem. The code below puts the values into the given fields on the pdf form, but in order to see those values in Adobe Reader, the fields themselves have to be selected. I can't share the pdf itself, but from opening it in Acrobat, it seems like security/protection isn't the issue, though I do get a permissions error when I set FormFlattening to True.
Is there a step in the code below which I'm missing?
Imports System
Imports System.IO
Imports System.Xml
Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.xml
Imports iTextSharp.pdfa
Imports System.Security
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pdfTemp As String = "C:\ExampleTemplate.pdf"
Dim newFile As String = "C:\NewFile.Pdf"
Dim pdfReader As New PdfReader(pdfTemp)
Dim pdfStamper As New PdfStamper(pdfReader, New FileStream(newFile,_ FileMode.Create), "\6c", True)
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
pdfFormFields.SetField("Date", "03092014", "03092014")
pdfFormFields.SetField("Contract_No", "1234456", "1234456")
pdfFormFields.SetField("Buyer", "bar, foo", "bar, foo")
pdfFormFields.GenerateAppearances = True
pdfStamper.FormFlattening = True
pdfStamper.Close()
pdfReader.Close()
End Sub
End Class
So it's not 100% clear to me why this worked and my previous efforts didn't, but copying and pasting this code to initialize the PdfStamper
Dim pdfTemplate As String = "Path to fillable pdf"
Dim strFolder As String = "Path to destination Folder"
Dim newFile As String = strFolder & "Name of Completed Form"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, New FileStream(newFile, FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields
`fields and values as in original question'
pdfStamper.FormFlattening = True
pdfStamper.Close()
from the tutorial here made the project work.
On a side note, it became clear to me that not all .pdf files with fillable fields are "forms", and that itextsharp requires that the file be a form. I realized this when, after applying the above code to two files successfully, the third failed, despite me knowing the names of the fields. To make it into a form, and thus recognizable to itextsharp, I opened it in acrobat and created a form. All the fields and their names were preserved so I saved it and it worked like a charm.