Friday, August 26, 2011

Fill PDF forms in C# with iTextSharp

Summary:
This tutorial is about using the iTextSharp library using C# in Visual Studio 2010


Description:
We will take user input from a Windows Forms project and place the input into the appropriate fields of an existing PDF document.


I fill out a lot of forms at work.  These forms never change.  Every week, I'm always using the same form and entering data in the same fields (on paper).  It seems like a perfect opportunity to make the process easier by doing it electronically.  


Before we start:
This tutorial assumes that you have an editable PDF with text fields named: "NAME", "ADDRESS", "CITY", and "STATE".  If I could post the template PDF to use as an example I would.  This is the only thing I can't provide with this tutorial.  If you can make a pdf file (somehow), and add the above listed textfields.  The rest of the tutorial should be easy.  If you want to substitute your own template PDF with editable text fields, rock on.  Pay special attention to matching the name (and case) of the PDF text field with the "fields.SetFields("pdf text field", string) parts.  


Steps:


  1. Download the iTextSharp library
  2. Extract the iTextSharp library
  3. Start new C# Windows Forms project
  4. Add reference to the iTextSharp library
  5. Add the needed controls (textboxes, buttons, labels) to our form
  6. Add a folder for the template PDF and place the PDF file in the folder
  7. Add the code to the project
  8. Done!! Check for the output file


1. Download iTextSharp
Download the iTextSharp library at http://sourceforge.net/projects/itextsharp/






2. Extract the iTextSharp library
Extract the library to a new folder that you can find again.  I extracted mine to my Visual Studio directory.  For example, "\Visual Studio 2010\external libraries\iText lib"


3. Create a new C# Windows Forms project
Start Visual Studio 2010.  Select "New Project".  Next, under C#, select "Windows Forms Application".  Name the solution something like "FormFillerPDF" and select "OK".


4.  Add a reference to the iTextSharp library
In your Solution Explorer, right click on "Reference".  Left-click on "Add Reference..." (Figure 4.1)
(Alternatively, you can also select "Project" then "Add Reference..." from the menu.)  Now you'll need to find the folder where you extracted the iTextSharp library in step 2. In that location, find "itextsharp.dll" and select "OK".  (Figure 4.2) 




Figure 4.1




Figure 4.2


5.  Add the needed controls to our form
Add five labels, four textbox, and two button controls to the form. (Figure 5.1)
Arange the controls the same way as they are arranged in Figure 5.1
Name the textboxes (from top to bottom): txtName, txtAddress, txtCity, txtState
Name the buttons (from left to right): btnReset, btnSubmit
Name the labels (from top to bottom): Name, Address, City, State 
Place the last label below everything else, name it "lblResult", and change the text to "Result: "


Figure 5.1


6,  Add a folder for the template PDF and place the PDF file in the folder
In the Solution Explorer, right-click on your project name (FormFillerPDF), and select "Add" then "New Folder".  Name the folder "PDF", place your template PDF in the folder.  Name your PDF file "BasePDF".


7.  Add the code to the project



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.IO; // This is for file access
using iTextSharp.text.pdf; // This is for iText


namespace FormFillerPDF
{
    public partial class frmFiller : Form
    {
        public frmFiller()
        {
            InitializeComponent();
        }


        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {


                // get the file paths


                // Template file path
                string formFile = "PDF\\BasePDF.pdf";
                
                // Output file path
                string newFile = "PDF\\Filled-out Form.pdf";                


                // read the template file
                PdfReader reader = new PdfReader(formFile);


                // instantiate PDFStamper object
                // The Output file will be created from template file and edited by the PDFStamper
                PdfStamper stamper = new PdfStamper(reader, new FileStream(
                            newFile, FileMode.Create));


                // Object to deal with the Output file's textfields
                AcroFields fields = stamper.AcroFields;


                // set form fields("Field Name in PDF", "String to be placed in this PDF text field");
                fields.SetField("NAME", txtName.Text);
                fields.SetField("ADDRESS", txtAddress.Text);
                fields.SetField("CITY", txtCity.Text);
                //fields.SetField("STATE", txtState.Text);


                // form flattening rids the form of editable text fields so
                // the final output can't be edited
                stamper.FormFlattening = true;


                // closing the stamper
                stamper.Close();                


                // If the code above works, we should see the following
                lblResult.Text = "Result: Success";


                // After everything is done, we are setting the textbox text properties to ""
                btnReset_Click(sender, e);


            }


            catch (Exception ex)
            {
                // Make my exception's visible (if any)
                lblResult.Text = ex.ToString();
            }            
        }


        private void btnReset_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtState.Text = "";
        }
    }
}





8.  Done!!! Check for the output file.  Look for the file "Filled-out Form.pdf".  It will be located in your project directory\bin\debug




Comments/Questions?
I'm always wanting to improve the quality of the content here.  If you have questions, want to see a better explanation, a better picture, let me know.  Thanks - Sean








13 comments:

  1. Replies
    1. Thanks, I'll double-check. What's not working?

      Delete
  2. thank you so much .. this works like a charm :)

    ReplyDelete
  3. You can create form and manage form fields in C# with Aspose.PDF for .NET Library. Try it i hope you will find it useful also.

    ReplyDelete
  4. Thank you so much! I converted this to an MVC 4 project, and it is great. Thanks especially for the "flattening" tip which I didn't know about. iTextSharp is the best thing since sliced bread.

    ReplyDelete
  5. you can try this free online pdf to text converter to convert pdf to text online.

    ReplyDelete
  6. c# add text pdf file is download for free on rasteredge http://www.rasteredge.com/how-to/csharp-imaging/pdf-text-edit-insert/

    ReplyDelete
  7. how can i extend from content...
    for example if i have 5 address, in my template I kept only 1 Address field (section) , and based on number of addresses i want to append it into the pdf file. Do you know hot to achieve it.

    ReplyDelete
  8. how can i extend form content...
    for example if i have 5 address, in my template I kept only 1 Address field (section) , and based on number of addresses i want to append the address into the pdf file. Do you know hot to achieve it.

    ReplyDelete
  9. Hello i have a problem i cannot get my fields of pdf i used this code using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
    using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
    {
    // Open existing PDF
    var pdfReader = new PdfReader(existingFileStream);

    // PdfStamper, which will create
    var stamper = new PdfStamper(pdfReader, newFileStream);

    var form = stamper.AcroFields;
    var fieldKeys = form.Fields.Keys;
    form.SetFieldRichValue("First Pdf File made by Salman using iText", "iglimaskafirst");
    foreach (string fieldKey in fieldKeys)
    {
    form.SetField(fieldKey, "REPLACED!");
    }
    but it null values of field

    ReplyDelete
  10. Fill PDF forms in C# with iTextSharp is very powerful and can do various operations on PDF files, but without the C# pdf to image function, I hope that bloggers can do more functions and make this Lib better.

    ReplyDelete
  11. Thank you for sharing this information. Using best pdf read app you can easily add details in pdf documents in less time.

    ReplyDelete
  12. With iTextSharp in C#, effortlessly fill PDF forms programmatically, streamlining data entry processes and enhancing document automation capabilities. I recommended to use zetpdf.com

    ReplyDelete