How to set a default selection for a radio button field in a PDF using C#
The Syncfusion Essential® PDF is a feature-rich and high performance .NET PDF library used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can choose the default value for radio button field in PDF document using C#.
Steps to choose default value for radio button field in PDF document programmatically:
- Create a new console application project.
- Install the Syncfusion.Pdf.Net.Core NuGet package as a reference to your console application from Nuget.org.
- Include the following namespaces in the Program.cs file.
C#
using Syncfusion.Pdf.Interactive;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Drawing;
- Use the following code sample in Program.cs to choose default value for radio button field in PDF document.
C#
// Create a new PDF document
PdfDocument document = new PdfDocument();
// Add a new page to the PDF document
PdfPage page = document.Pages.Add();
// Create a new radio button list field
PdfRadioButtonListField radioButtonList = new PdfRadioButtonListField(page, "employeesRadioList");
// Create a font
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Regular);
// Create a new radio button item for "Male"
PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("Male");
// Set the bounds for the radio button item
radioItem1.Bounds = new RectangleF(90, 203, 15, 15);
// Draw the label "Male"
page.Graphics.DrawString("Male", font, PdfBrushes.Black, new RectangleF(110, 204, 180, 20));
// Add the radio button item to the radio button list
radioButtonList.Items.Add(radioItem1);
// Create a new radio button item for "Female"
PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("Female");
// Set the bounds for the radio button
radioItem2.Bounds = new RectangleF(205, 203, 15, 15);
// Draw the label "Female"
page.Graphics.DrawString("Female", font, PdfBrushes.Black, new RectangleF(225, 204, 180, 20));
// Add the radio button item to the list
radioButtonList.Items.Add(radioItem2);
//Set the default selection value index
radioButtonList.SelectedIndex = 1;
// Add the radio button list to the form
document.Form.Fields.Add(radioButtonList);
//Save the document into stream.
MemoryStream stream = new MemoryStream();
document.Save(stream);
//Close the document.
document.Close(true);
// Write the contents of the memory stream to a file
File.WriteAllBytes("Output.pdf", stream.ToArray());
A complete working sample can be downloaded from Default_Value_For_Radio_Button.zip
By executing the program, you will get the PDF document as follows.
Take a moment to peruse the documentation for working with forms, where you will find other options like creating, removing, modifying, and filling form fields in PDF document.
Refer here to explore the rich set of Syncfusion Essential® PDF features.