This tutorial shows you how to fill data in a pdf form using itextsharp in c sharp code.
As you know, ITextSharp is an open source that's help you read and write data to a pdf file
You can download and install the itextsharp library from Manage Nuget Packages or you can download it directly from https://www.nuget.org/packages/iTextSharp/
To play the demo, you need to create a pdf form. You can use the acrobat adobe software to create a pdf form, then you can read a pdf form by using itextsharp library.
Next, we will read json data and find the fields of your pdf form, then fill your data corresponding to the field of your pdf form
public void FillInPdfForm()
{
PdfReader pdfReader = new PdfReader(Application.StartupPath + "\\HRForm.pdf");
List<string> fields = new List<string>();
foreach (var de in pdfReader.AcroFields.Fields)
fields.Add(de.Key);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(Application.StartupPath + "\\HRForm_Fill.pdf", FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
pdfFormFields.GenerateAppearances = true;
string json = @"[{""templateid"": ""29cf6a79-00fa-41d0-8791-fa46e1f47011""},{""firstname"": ""Tan"",""lastname"": ""Hynh"",""email"": ""[email protected]"",""address"": ""ABC""}]";
dynamic data = JArray.Parse(json) as JArray;
foreach (dynamic d in data)
{
foreach (JProperty p in d)
{
if (fields.Contains(p.Name))
{
pdfFormFields.SetField(p.Name, p.Value.ToString());
}
}
}
pdfStamper.FormFlattening = true;
pdfStamper.Close();
}
I've created a json variable to store the json data
string json = @"[{""templateid"": ""29cf6a79-00fa-41d0-8791-fa46e1f47011""},{""firstname"": ""Tan"",""lastname"": ""Hynh"",""email"": ""[email protected]"",""address"": ""ABC""}]";
Json data is an array with teamplateid field and user information fileds
Don't forget to add the using namespaces
using iTextSharp.text.pdf;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
I hope you can solve the problem of filling the data in a pdf form in C#