In This Topic
    Replace text
    In This Topic

    Introduction

    The following example demonstrates how to replace the text found in a PDF document. It also briefly covers how to find specific text in a page.

    Replace text (C#)
    Copy Code
    public static void ReplaceText()
    {
      Console.WriteLine( "=== REPLACE TEXT ===" );
      var outputFileName = "ReplaceText.pdf";
      var outputPath = TextsSample.TextsSampleOutputDirectory + outputFileName;
    
      // Loads a PdfDocument.
      using( var pdfInput = PdfDocument.Load( TextsSample.TextsSampleResourcesDirectory + @"Two Page Text Only - from libre office.pdf" ) )
      {
        // Gets the first Page. 
        var page = pdfInput.Pages.First();
    
        var test = page.Text;
    
        // Set the text to find in a specific area of the page.
        var textSearchOptions = new TextSearchOptions( "License" ) { Area = new Rectangle( new Point( 200, 50 ), new Point( 400, 108 ) ) };
    
        // Get all the texts matching the search options in page 1.
        var textMatches = page.FindText( textSearchOptions );
    
        // Replace the found texts with a red CourierBoldOblique font of size 16 new text.
        var newTextStyle = TextStyle.WithFontAndBrush( pdfInput.Fonts.GetStandardFont( StandardFontType.CourierBoldOblique ), 16d, Brushes.Red );
        page.ReplaceText( textMatches, "Details", newTextStyle );
    
        // Saves to the output document.
        pdfInput.SaveAs( outputPath );
        Console.WriteLine( $"Info exported to path: {outputFileName}" );
      }
    }


    See Also