I have added form field to an existing PDF using "PdfPageBase page = doc.Pages[0];" . Then i try to open created pdf for setting form field values from database but i am not able to read form field
But when i added form field to PDF created by " PdfPageBase page = doc.Pages.Add()" i am able to read form field.
I am using FreeSpire.pdf .net library - version 8.6.0
Below is my code
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Blank.pdf");
//Add a page
//PdfPageBase page = doc.Pages.Add();
doc.AllowCreateForm = (doc.Form == null) ? true : false;
PdfPageBase page = doc.Pages[0];
SizeF size = page.Size;
PdfPageBase newPage;
//Initialize x and y coordinates
float baseX = 100;
float baseY = 30;
//Create two brush objects
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.Black));
//Create a font
PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);
//Add a textbox
page.Canvas.DrawString("TextBox:", font, brush1, new PointF(10, baseY));
RectangleF tbxBounds = new RectangleF(baseX, baseY, 150, 15);
PdfTextBoxField textBox = new PdfTextBoxField(page, "textbox");
textBox.Bounds = tbxBounds;
textBox.Text = "Hello World";
textBox.Font = font;
doc.Form.Fields.Add(textBox);
baseY += 25;
//Save to file
MemoryStream stream = new MemoryStream();
doc.SaveToStream(stream);
// pdfTemplate = stream.ToArray();
doc.SaveToFile("FillableForms.pdf", FileFormat.PDF);
//Fill Form
PdfDocument doc1 = new PdfDocument();
//doc1.LoadFromFile(@"FillableForms.pdf");
doc1.LoadFromBytes(stream.ToArray());
PdfFormWidget form = (PdfFormWidget)doc1.Form;
PdfFormFieldWidgetCollection formWidgetCollection = form.FieldsWidget;
for (int i = 0; i < formWidgetCollection.Count; i++)
{
PdfField field = formWidgetCollection[i];
if (field is PdfTextBoxFieldWidget)
{
if (field.Name == "textbox")
{
PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field;
textBoxField.Text = "Kaila Smith";
}
}
}
PdfForm form1 = (PdfForm)doc1.Form;
PdfFormFieldCollection formCollection = form1.Fields;
for (int i = 0; i < formCollection.Count; i++)
{
PdfField field = formCollection[i];
if (field is PdfTextBoxField)
{
if (field.Name == "textbox")
{
PdfTextBoxField textBoxField = (PdfTextBoxField)field;
textBoxField.Text = "Kaila Smith";
}
}
}
if (doc1.Form is PdfForm formWidget)
{
foreach (PdfField field in formWidget.Fields.List)
{
if (field is PdfTextBoxField)
{
var textBoxField = field as PdfTextBoxField;
textBoxField.Text = "tulesh";
}
}
}