How to replace the existing text in the PDF document?
We can replace the existing text in the PDF document by drawing the replacement text on the graphics using the following methods,
1)Retrieve the bounds of the searched text using the FindText method. FindText method returns the bounds of the searched text across all the pages.
Dictionary<int, List<RectangleF>> matchedTextbounds = new Dictionary<int, List<RectangleF>>();
//Loads the PDF document. PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../Data/PDFDocument.pdf");
// Retrieves the bounds of the searched text using FindText method. loadedDocument.FindText("Pdf", out matchedTextbounds);
|
2)Iterate through the retrieved bounds from FindText method and fill the rectangle with white color like below,
PdfLoadedPage page = null;
// Font which is used to draw the replacement text. PdfFont font = new PdfTrueTypeFont(new Font("Arial", 11));
// Iterate throught the pages of the PDF document. for (int i =0;i< matchedTextbounds.Count;i++) { page= (PdfLoadedPage)loadedDocument.Pages[i];
// Iterate through the instance of the searched text in page. foreach (RectangleF rectangle in matchedTextbounds[i]) { // Draws the white filled rectangle over the searched text. page.Graphics.DrawRectangle(PdfBrushes.White, rectangle);
// Draws the replacedment text with respect to the font and bounds of the searched text. page.Graphics.DrawString("PDF", font, PdfBrushes.Black, rectangle.X-2, rectangle.Y-2); } } // Saves the PDF document to specified location. loadedDocument.Save("../../Data/PDFDocument_Replaced.pdf");
|
Remark:
1) Background color will not always be white color.
2)Font, style and size of the newly added text will not be same as the other text in the paragraph.
3)The replaced text should occupy the same space occupied by the older text, if it occupies more space it might lead to text overlap.
We have also created a sample with the above code example and the sample can be downloaded from the following link,
https://www.syncfusion.com/downloads/support/directtrac/general/ze/ExtractTextFromRegion284615895