Using itextsharp (or any c# pdf library), how to open a PDF, replace some text, and save it again?

Chris picture Chris · Nov 19, 2010 · Viewed 37.2k times · Source

Using itextsharp (or any c# pdf library), i need to open a PDF, replace some placeholder text with actual values, and return it as a byte[].

Can someone suggest how to do this? I've had a look at the itext docs and can't figure out where to get started. So far i'm stuck on how to get the source pdf from a PDFReader to a Document object, i presume i'm probably approaching this the wrong way.

Thanks a lot

Answer

Chris picture Chris · Nov 19, 2010

In the end, i used PDFescape to open my existing PDF file, and place some form fields in where i need to put my fields, then save it again to create my PDF file.

http://www.pdfescape.com

Then i found this blog entry about how to replace form fields:

http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/

All works nicely! Here's the code:

public static byte[] Generate()
{
  var templatePath = HttpContext.Current.Server.MapPath("~/my_template.pdf");

  // Based on:
  // http://www.johnnycode.com/blog/2010/03/05/using-a-template-to-programmatically-create-pdfs-with-c-and-itextsharp/
  var reader = new PdfReader(templatePath);
  var outStream = new MemoryStream();
  var stamper = new PdfStamper(reader, outStream);

  var form = stamper.AcroFields;
  var fieldKeys = form.Fields.Keys;

  foreach (string fieldKey in fieldKeys)
  {
    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldA")
      form.SetField(fieldKey, "1234");
    if (form.GetField(fieldKey) == "MyTemplatesOriginalTextFieldB")
      form.SetField(fieldKey, "5678");
  }

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

  stamper.Close();
  reader.Close();

  return outStream.ToArray();
}