0

I'm trying to replace text in PDF using iTextSharp dll but its not working in all cases. PDF document doesn't have acro fields.

If the text which I need to replace is bigger than original text its not printing all characters. Finding some special characters is also not working.

I have tried this code

using (PdfReader reader = new PdfReader(sourceFileName))
{
    for (int i = 1; i <= reader.NumberOfPages; i++)
    {
        byte[] contentBytes = reader.GetPageContent(i);
        string contentString = PdfEncodings.ConvertToString(contentBytes, PdfObject.TEXT_PDFDOCENCODING);
        contentString = contentString.Replace("SOMETEXT", "NEWBIGGERTEXT");                 
        reader.SetPageContent(i, PdfEncodings.ConvertToBytes(contentString, PdfObject.TEXT_PDFDOCENCODING));
    }
    new PdfStamper(reader, new FileStream(newFileName, FileMode.Create, FileAccess.Write)).Close();
}

Please let me know how this can be achieved.

Bassie
  • 9,529
  • 8
  • 68
  • 159
  • 1
    I'll see if I can find a more comprehensive answer I've written somewhere, but the short story is: Pdf is not meant to be an editable format, so while you can technically replace text, the operations have some hidden pitfalls and difficulties, and it seems you have encountered one of them. – Samuel Huylebroeck Jan 19 '17 at 08:13
  • That your code merely is *not working in all cases*, indicates that you have mostly tested with very simple pdfs. If you try your code on many current pdfs, your code likely to always fail. – mkl Jan 19 '17 at 09:24

0 Answers0