How to modify PDF file using iTextSharp

Step 1: First you need to stamp the PDF file using PDF stamper ( For example: for first name, last name etc.)
Step 2: Download iTextSharp dll and add reference to your solution.
Step 3: Modify the Below code as per your requirement.

void textwriter()
{
string fileNameExisting = @”C:\Users\amar.prakash\Desktop\SC.pdf”;
string fileNameNew = @”C:\Users\amar.prakash\Desktop\NewSC.pdf”;

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;

foreach (string fieldKey in fieldKeys)
{
//if (fieldKey.StartsWith(“T”))
// form.SetField(fieldKey, “REPLACED!”);
//if (fieldKey.StartsWith(“c”))
// form.SetField(fieldKey, “Yes”);
if (fieldKey.Equals(“Text1”))
form.SetField(fieldKey, “ABC Inc”);
if (fieldKey.Equals(“Text2”))
form.SetField(fieldKey, “Amar”);
if (fieldKey.Equals(“Text3”))
form.SetField(fieldKey, “Anand”);
if (fieldKey.Equals(“Text4”))
form.SetField(fieldKey, “REPLACED!”);
}

// “Flatten” the form so it wont be editable/usable anymore
stamper.FormFlattening = true;

// You can also specify fields to be flattened, which
// leaves the rest of the form still be editable/usable
stamper.PartialFormFlattening(“field1”);

stamper.Close();
pdfReader.Close();
}

This entry was posted in General and tagged , . Bookmark the permalink.

2 Responses to How to modify PDF file using iTextSharp

  1. Christian says:

    Hi, thank you for the post. But this line generate a error of Object non instantiated:

    var stamper = new PdfStamper(pdfReader, newFileStream);

    • admin says:

      Hi Christian, please make sure you followed the 1st step.

      Step 1: First you need to stamp the PDF file using PDF stamper ( For example: for first name, last name etc.)

Leave a Reply

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