We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Need to find/replace text in PDF without altering layout

All,

I am trying to find and replace text in a PDF.  However, when I do so, my PDF format changes completely.  Here is my code:

                   PdfLoadedDocument loadedDocument = new PdfLoadedDocument(GetStreamFromUrl(inputFile));
            logger.Info($"Successfully got PDF Loaded Document from {inputFile}.");

            PdfLoadedPageCollection loadedPages = loadedDocument.Pages;
            PdfDocument newPdfDocument = new PdfDocument();
            foreach (PdfPageBase page in loadedPages)
            {
                string extractedText = page.ExtractText();
                foreach (var item in bindVarDictionary)
                {
                    extractedText = extractedText.Replace(item.Key, item.Value);
                }
                PdfPage newPage = newPdfDocument.Pages.Add();

                //Create PDF graphics for the page
                PdfGraphics graphics = newPage.Graphics;

                //Set the standard font.
                PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

                //Draw the text.
                graphics.DrawString(extractedText, font, PdfBrushes.Black, new PointF(0, 0));
            }

Does anyone know how I can do a simple find/replace of text in a PDF without totally changing my formatting?

Thanks,

Philip

3 Replies

SK Surya Kumar Syncfusion Team July 10, 2017 09:55 AM UTC

Hi Philip, 
 
Thank you for using Syncfusion products. 
 
At present, we do not have support for performing find and replace text in a PDF document and we have logged feature request for “Need to add support for performing find and replace text in existing PDF document ” in our feature management system. We will let you know once this feature is implemented. 
 
Regards,
Surya Kumar 



RR Rangita Rajakumar November 20, 2024 07:32 PM UTC

any update on this?



IJ Irfana Jaffer Sadhik Syncfusion Team November 21, 2024 07:48 AM UTC

Hi Rangita,


We do not have any immediate plan to implement this feature on our end. 

we have prepared a simple workaround with the following steps:


1. Load the document.

2. Find the text and preserve all matching bounds.

3. Iterate through the pages with the matched bounds and use the extract text feature to retrieve the font details.

4. Perform redaction over the matched bounds using the text-only API.

5. Draw the string with the extracted font details over the redacted area.

6. Save the final PDF document.




Please try this on your end and let us know the outcome.

Please follow the below links for more information:

Regards,
Irfana J



Loader.
Up arrow icon