How To Fill Editable PDF Using C#

This article describes that how to fill editable PDF using C# Code and iTextSharp DLL. iTextSharp is a very popular library for working with PDFs.

The Sample PDF

Add NuGet Package

Add iTextSharp DLL library in your .Net application.

Here is my C# Code

Here, I’m filling the first name, last name, and profession using c# code and after that, I’m saving this pdf with another name.

static void Main(string[] args)
        {
            Console.WriteLine("Start Filling");
            MemoryStream memoryStream = new MemoryStream();
            MemoryStream blacklistmemoryStream = new MemoryStream();

            //Set the Path
            PdfReader pdfReader = new PdfReader("D:/SamplePdf.pdf");
            using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
            {
                pdfStamper.FreeTextFlattening = true;
                AcroFields fields = pdfStamper.AcroFields;

                if (fields.Fields.Count > 0)
                {
                    //Set The PDF Fields
                    fields.SetField("FirstName", "Chand");
                    fields.SetField("LastName", "Dakhara");
                    fields.SetField("Profession", "Web Developer");

                    fields.GenerateAppearances = pdfStamper.FormFlattening = true;
                    pdfStamper.Writer.CloseStream = false;
                    pdfStamper.Close();
                    memoryStream.Position = 0;

                    //Save New PDF After filling
                    string SaverPath = "D:/FilledSamplePdf.pdf";
                    byte[] data;
                    using (Stream inputStream = memoryStream)
                    {
                        MemoryStream PDFmemoryStream = inputStream as MemoryStream;
                        if (PDFmemoryStream == null)
                        {
                            PDFmemoryStream = new MemoryStream();
                            inputStream.CopyTo(PDFmemoryStream);
                        }
                        data = memoryStream.ToArray();
                        System.IO.File.WriteAllBytes(SaverPath, data);
                    }

                    Console.WriteLine("\nDone");
                    Console.WriteLine("\n\nPress any key to close console window");
                    Console.ReadKey();
                }
                else
                {
                    Console.WriteLine("\n No Textbox found");
                    Console.WriteLine("\n\nPress any key to close console window");
                    Console.ReadKey();
                }
            }
        }

Output

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories