Pdfsharp replace text

PDFsharp is a popular library for creating and manipulating PDF documents in .NET. It provides various functionalities to work with PDF documents, including replacing text.

To replace text in a PDF document using PDFsharp, you need to follow these steps:

  1. Load the existing PDF document using the PdfReader class.
  2. Iterate through the pages of the document using a loop.
  3. For each page, create a new XGraphics object to draw on the page.
  4. Use the XTextFormatter class to extract text from the existing page.
  5. Search for the text you want to replace and replace it with the desired text.
  6. Finally, save the modified document using the PdfDocument class.

Here’s an example code snippet demonstrating how to replace text in a PDF document using PDFsharp:

// Load the existing PDF document
using (PdfDocument document = PdfReader.Open("existing.pdf", PdfDocumentOpenMode.Modify))
{
    // Iterate through the pages
    foreach (PdfPage page in document.Pages)
    {
        // Create a new XGraphics object to draw on the page
        using (XGraphics gfx = XGraphics.FromPdfPage(page))
        {
            // Create a new XTextFormatter object to extract text from the page
            XTextFormatter tf = new XTextFormatter(gfx);
            
            // Extract the existing text from the page
            string existingText = tf.GetText(page);
            
            // Replace the desired text
            string modifiedText = existingText.Replace("old text", "new text");
            
            // Clear the page
            gfx.DrawString("", XFont.Default, XBrushes.White, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center);
            
            // Draw the modified text on the page
            tf.DrawString(modifiedText, XFont.Default, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.TopLeft);
        }
    }
    
    // Save the modified document
    document.Save("modified.pdf");
}
    

Make sure to replace the “existing.pdf” and “modified.pdf” strings with the actual file paths of your input and output PDF files respectively. The code above assumes that the old text to be replaced is “old text” and the new text is “new text”. Adjust them based on your specific requirements.

Remember to add the necessary references to the PDFsharp library in your project to compile and run the code successfully.

Leave a comment