How to update PDF without creating a new PDF?
I need to replace a word in an existing PDF AcroField with a different word. I am using PDFStamper from iTEXTSHARP to do the same and it works fine. But this requires a new PDF to be created and I would like the changes to be reflected in the existing PDF. If I set the destination filename to be the same as the original filename, then no changes are reflected. I am new to iTextSharp, is there anything I am doing wrong? Please help .. I am providing a piece of code that I am using
private void ListFieldNames(string s)
{
try
{
string pdfTemplate = @"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
string newFile = @"z:\TEMP\PDF\PassportApplicationForm_Main_English_V1.0.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
PdfReader reader = new PdfReader((string)pdfTemplate);
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create, FileAccess.ReadWrite)))
{
AcroFields form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
foreach (string fieldKey in fieldKeys)
{
//Replace Address Form field with my custom data
if (fieldKey.Contains("Address"))
{
form.SetField(fieldKey, s);
}
}
stamper.FormFlattening = true;
stamper.Close();
}
}
}
source to share
As stated in my book iText in Action , you cannot read a file and write to it at the same time. Think about how Word works: You can't open a Word document and write directly to it. Word always creates a temporary file, writes the changes to it, then replaces the original file, and then deletes the temporary file.
You can also do this:
- read the original file with
PdfReader
, - create a temporary file for
PdfStamper
, and when you're done, - replace the original file with a temporary file.
Or:
- read the source file into
byte[]
, - create
PdfReader
with thisbyte[]
and - use source path for
PdfStamper
.
This second option is more dangerous as you will lose the original file if you do anything that throws an exception in PdfStamper
.
source to share