Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

Replace the text in pdf document using itextSharp

I want to replace a particular text in PDF document. I am currently using itextSharp library to play with PDF documents.

I had extracted the bytes from pdfdocument and then replaced that byte and then write the document again with the bytes but it is not working. In the below example I am trying to replace string 1234 with 5678

Any advise on how to perform this would be helpful.

PdfReader reader = new PdfReader(opf.FileNames[i]);
byte[] pdfbytes = reader.GetPageContent(1);

PdfString oldstring = new PdfString("1234");
PdfString newstring = new PdfString("5678");
byte[] byte1022 = oldstring.GetOriginalBytes();
byte[] byte1067 = newstring.GetOriginalBytes();
int position = 0;
for (int j = 0; j <pdfbytes.Length ; j++)
{
    if (pdfbytes[j] == byte1022[0])
    {
        if (pdfbytes[j+1] == byte1022[1])
        {
            if (pdfbytes[j+2] == byte1022[2])
            {
                if (pdfbytes[j+3] == byte1022[3])
                {
                    position = j;
                    break; 
                }
            }
        }

    }

}

pdfbytes[position] = byte1067[0];
pdfbytes[position + 1] = byte1067[1];
pdfbytes[position + 2] = byte1067[2];
pdfbytes[position + 3] = byte1067[3];
File.WriteAllBytes(opf.FileNames[i].Replace(".pdf","j.pdf"), pdfbytes);

Upvotes: 0

Views: 4018

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77606

What makes you think 1234 is part of the page's content stream and not of a form XObject? Your code is never going to work in general if you don't parse all the resources of a page.

Also: I see GetPageContent(), but I don't see you using SetPageContent() anywhere. How are the changes ever going to be stored in the PdfReader object?

Moreover, I don't see you using PdfStamper to write the altered PdfReader contents to a file.

Finally: I'm to shy to quote the words of Leonard Rosenthol, Adobe's PDF Architect, but ask him, and he'll tell you personally that you shouldn't do what you're trying to do. PDF is NOT a format for editing.Read the intro of chapter 6 of the book I wrote on iText: http://www.manning.com/lowagie2/samplechapter6.pdf

Upvotes: 2

Related Questions