New to Telerik Document Processing? Download free 30-day trial

How to replace text in PDF

Environment

Product Version Product Author
2021.2.615 RadPdfProcessing Tanya Dimitrova

Description

With PdfProcessing, you can import a PDF document and traverse the text inside to replace specific matches. This is done by iterating the TextFragment objects and modifying their Text property when needed.

Solution

The following code iterates the TextFragments on each RadFixedPage and replaces the "<%textfield,1234%>" string with "replaced text".

foreach (RadFixedPage page in document.Pages) 
{ 
    foreach (ContentElementBase contentElement in page.Content) 
    { 
        if (contentElement is TextFragment) 
        { 
            TextFragment textFragment = (TextFragment)contentElement; 
 
            string replacedText = "replaced text"; 
 
            Replace(textFragment, "<%textfield,1234%>", replacedText); 
        } 
    } 
} 
And here is the implementation of the Replace method:

private static void Replace(TextFragment textFragment, string oldValue, string newValue) 
{ 
    if (textFragment.Text.Contains(oldValue)) 
    { 
        textFragment.Text = newValue; 
    } 
} 

Notes

We have also logged requests to improve the API and provide you with an easy way for searching and replacing text. You can vote for their implementation and subscribe to the requests if you would like to receive updates about status changes on them using the related public items:

In this article
Not finding the help you need? Improve this article