Skip to content

Fill and flatten a PDF form in C#

Since 1.1View as Markdown

Fill an interactive PDF form from code, then make the values part of the page.

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.

recipe-fill-and-flatten-pdf-form.cs
#:package PdfNetStack@1.2.0
using 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 removed
doc.Save("application-filled.pdf");

The application form with a name, a checked box, the pro plan and Morocco filled in

  • Field names are fully qualified: a field city inside address is address.city. doc.Form.Fields lists them all.
  • Skip Flatten to 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.