Fill and flatten a PDF form in C#
Fill an interactive PDF form from code, then make the values part of the page.
Short answer
Section titled “Short answer”Look fields up by name in doc.Form, cast to the field type, and set the value. Setting a value
redraws the field’s appearance, so the filled form looks the same in every viewer. Flatten
stamps the appearances into the pages and removes the form, so the values can no longer be edited.
#:package PdfNetStack@1.2.0using PdfNetStack;
PdfDocument doc = PdfDocument.Open("application.pdf");((PdfTextField)doc.Form["name"]!).Text = "Jamal Abdelkhalek";((PdfCheckBoxField)doc.Form["subscribe"]!).Checked = true;((PdfRadioButtonField)doc.Form["plan"]!).Selected = "pro";((PdfChoiceField)doc.Form["country"]!).Select("Morocco");doc.Form.Flatten(); // values become page content, the form is removeddoc.Save("application-filled.pdf");
- Field names are fully qualified: a field
cityinsideaddressisaddress.city.doc.Form.Fieldslists them all. - Skip
Flattento keep the form editable after filling it. - A font the form embeds whole is reused for the new appearance; others map to the closest standard font.
Related
Section titled “Related”- Forms: reading, filling, flattening and creating fields
- API: PdfAcroForm, PdfTextField, PdfChoiceField