PDF text replace not working

2019-09-14 18:32发布

问题:

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.

标签: c# itext