Introduction

Aspose.Pdf for .NET/Core/Standard 2.0 is a PDF manipulation component. This example shows how to you can replace text in PDF  using an Aspose.Pdf.Facades.PdfContentEditor class.

Building the Sample

To build the sample you can use any edition of Visual Studio 2017. All the necessary files are referenced from NuGet and will be automatically downloaded from there. This sample also can be built in Visual Studio Code. After the build, you can run the demo application in console.

Description

The easiest way to replace text in PDF is using Aspose.Pdf.Facades.PdfContentEditor.ReplaceText() method. This sample contains two demonstrations: a simple replacement of one text segment to another and a replacement with font settings.

Steps involved

  1. Create an instance of Document class and open the PDF document;
  2. Create an instance of PdfContentEditor and bind the document;
  3. Set text replacement strategy - find first or find all text occurrences;
  4. Run the ReplaceText method.

In the simplest case, the code will look like it's shown below:

C#
Edit|Remove
var pdfDocument = new Aspose.Pdf.Document(@".\Data\demo.pdf"); 
var pdfContentEditor = new Aspose.Pdf.Facades.PdfContentEditor(); 
 
pdfContentEditor.BindPdf(pdfDocument); 
pdfContentEditor.TextReplaceOptions.ReplaceScope = TextReplaceOptions.Scope.REPLACE_FIRST; 
pdfContentEditor.ReplaceText("TextToFind""TextToReplace");

This example uses a PDF document with an invitation template for a music contest. The ReplaceTextExampleSimple shows the replacement of single fragments such as dates and general info and repeated fragments such as contest title.

The ReplaceTextExampleWithFontSettings method does the same, but some of the text fragments will be decorated as red text with 14pt size.

More Information