AcroForms and Form Flattening
PDFsharp is a .NET library for creating and modifying PDF documents.
Brought to you by:
pdfsharp,
stefan_lange
I need some help with Acro Forms.
I have this code:
PdfDocument doc = PdfReader.Open(fileName);
doc.AcroForm.Fields["title"].Value = new PdfString("My Title");
doc.Save(newFileName)
1. When I open the PDF, the field is empty, but when I click it, then it shows the "My Title" value. Is it a bug or I must set this value somewhere else?
and 2. Is there any way to do "form flattening" after filling the AcroForms?
Thanks.
I could not get this object:
doc.AcroForm.Fields["title"].Value = new PdfString("My Title");
created. Was there something else I need to do?
Having a similiar problem...I"m losing the formatting as well with this code.
Help!
// Open the file
PdfDocument document = PdfReader.Open(Filename, PdfDocumentOpenMode.Modify);
// Get the root object of all interactive form fields
PdfAcroForm form = document.AcroForm;
// Get all form fields of the whole document
PdfTextField.PdfAcroFieldCollection fields = form.Fields;
// Value the fields.
PdfTextField t = (PdfTextField)fields[Field_MMDDYYYY];
t.Text = ClinicDate;
I'm trying to figure out the type of the field that is coming back but for some reason the object keeps changing. Open any PDF that has form fields on it and try to determine the field type. TextField, CheckboxField, etc...
Dim sFilename As String = txtFileName.Text
Dim sResults As String = ""
Dim oDoc As PdfDocument = PdfReader.Open(sFilename, PdfDocumentOpenMode.Modify)
Dim oForm As AcroForms.PdfAcroForm = oDoc.AcroForm
Dim oFields As AcroForms.PdfTextField.PdfAcroFieldCollection
Dim oFld As Object
Dim oHld As Object
Dim idx As Long
oFields = oDoc.AcroForm.Fields
For idx = 0 To oFields.Elements.Count - 1
'oFields.Elements.Items(0).value()
If TypeOf DirectCast(oFields.Elements.Items(idx), PdfSharp.Pdf.Advanced.PdfReference).Value Is AcroForms.PdfTextField Then
sResults += "TextBox" + vbCrLf
ElseIf TypeOf DirectCast(oFields.Elements.Items(idx), PdfSharp.Pdf.Advanced.PdfReference).Value Is AcroForms.PdfCheckBoxField Then
sResults += "CheckBox" + vbCrLf
ElseIf TypeOf DirectCast(oFields.Elements.Items(idx), PdfSharp.Pdf.Advanced.PdfReference).Value Is AcroForms.PdfRadioButtonField Then
sResults += "RadioButton" + vbCrLf
End If
Next
This is necessary, otherwise it is only visible when clicking into the field
document.AcroForm.Elements["/NeedAppearances"] = new PdfBoolean(true);
var nameField = document.AcroForm.Fields["Name"]!;
nameField.Value = new PdfString($"Test {DateTime.Now}");
Last edit: JOAO PAULO MOREIRA ANTUNES 2025-01-10