Chris Chris - 5 months ago 36
C# Question

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

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


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.

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

All works nicely! Here's the code:

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

  // Based on:
  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;  


  return outStream.ToArray();