> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/core/get-started/samples/contentreplacertest.md).

# Search & Replace PDF String, Text, Images - ContentReplacer

Sample code to use Apryse SDK for searching and replacing text strings and images inside existing PDF files (e.g. business cards and other PDF templates). Unlike PDF forms, the ContentReplacer works o

Sample code to use Apryse SDK for searching and replacing text strings and images inside existing PDF files (e.g. business cards and other PDF templates). Unlike PDF forms, the ContentReplacer works on actual PDF content and is not limited to static rectangular annotation regions. Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our [Server SDK](/core/get-started/get-started.md) and [PDF Editing & Manipulation Library](/core/page-manipulation/manipulation.md).

{% hint style="info" %}
It's mandatory to use square brackets for target strings in the original PDF doc when using `ContentReplacer` methods like `AddString()`. Otherwise, the content replacer won't recognize it as a template to replace.

For example, in the PDF document, you add a template for recognition: \[NAME]. In the code, you tie the tag specified within the square brackets to what you want it to be replaced with: `replacer.AddString("NAME", "John Smith")` . After processing, both the square brackets and the tag will be replaced with "John Smith".
{% endhint %}

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

using System;
using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

namespace ContentReplacerTestCS
{
	/// <summary>
	//-----------------------------------------------------------------------------------------
	// The sample code illustrates how to use the ContentReplacer class to make using 
	// 'template' pdf documents easier.
	//-----------------------------------------------------------------------------------------
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			// Relative path to the folder containing test files.
			string input_path = "../../../../TestFiles/";
			string output_path = "../../../../TestFiles/Output/";


			// The following example illustrates how to replace an image in a certain region,
			// and how to change template text.
			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf"))
				using (ContentReplacer replacer = new ContentReplacer())
				{
					doc.InitSecurityHandler();

					// first, replace the image on the first page
					Page page = doc.GetPage(1);
					Image img = Image.Create(doc, input_path + "peppers.jpg");
					replacer.AddImage(page.GetMediaBox(), img.GetSDFObj());
					// next, replace the text place holders on the second page
					replacer.AddString("NAME", "John Smith");
					replacer.AddString("QUALIFICATIONS", "Philosophy Doctor"); 
					replacer.AddString("JOB_TITLE", "Software Developer"); 
					replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd"); 
					replacer.AddString("ADDRESS_LINE2", "Vancouver, BC"); 
					replacer.AddString("PHONE_OFFICE", "604-730-8989"); 
					replacer.AddString("PHONE_MOBILE", "604-765-4321"); 
					replacer.AddString("EMAIL", "info@pdftron.com"); 
					replacer.AddString("WEBSITE_URL", "http://www.pdftron.com"); 
					// finally, apply
					replacer.Process(page);

					doc.Save(output_path + "BusinessCard.pdf", 0);
					Console.WriteLine("Done. Result saved in BusinessCard.pdf");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}


			// The following example illustrates how to replace text in a given region
			try
			{
				using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
				using (ContentReplacer replacer = new ContentReplacer())
				{
					doc.InitSecurityHandler();

					Page page = doc.GetPage(1);
					Rect target_region = page.GetMediaBox();
					string replacement_text = "hello hello hello hello hello hello hello hello hello hello";
					replacer.AddText(target_region, replacement_text);
					replacer.Process(page);

					doc.Save(output_path + "ContentReplaced.pdf", 0);
					Console.WriteLine("Done. Result saved in ContentReplaced.pdf");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
			Console.WriteLine("Done.");
		}
	}
}
```

{% endcode %}
{% endtab %}

{% tab title="Go" %}
{% code lineNumbers="true" %}

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
	"fmt"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

var inputPath = "../../TestFiles/"
var outputPath = "../../TestFiles/Output/"    

//-----------------------------------------------------------------------------------------
// The sample code illustrates how to use the ContentReplacer class to make using 
// 'template' pdf documents easier.
//-----------------------------------------------------------------------------------------

func main(){
	PDFNetInitialize(PDFTronLicense.Key)

	// Example 1) Update a business card template with personalized info

	doc := NewPDFDoc(inputPath + "BusinessCardTemplate.pdf")
	doc.InitSecurityHandler()

	// first, replace the image on the first page
	replacer := NewContentReplacer()
	page := doc.GetPage(1)
	img := ImageCreate(doc.GetSDFDoc(), inputPath + "peppers.jpg")
	replacer.AddImage(page.GetMediaBox(), img.GetSDFObj())
	// next, replace the text place holders on the second page
	replacer.AddString("NAME", "John Smith")
	replacer.AddString("QUALIFICATIONS", "Philosophy Doctor")
	replacer.AddString("JOB_TITLE", "Software Developer")
	replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd")
	replacer.AddString("ADDRESS_LINE2", "Vancouver, BC")
	replacer.AddString("PHONE_OFFICE", "604-730-8989")
	replacer.AddString("PHONE_MOBILE", "604-765-4321") 
	replacer.AddString("EMAIL", "info@pdftron.com")
	replacer.AddString("WEBSITE_URL", "http://www.pdftron.com")
	// finally, apply
	replacer.Process(page)

	doc.Save(outputPath + "BusinessCard.pdf", uint(SDFDocE_linearized))
	doc.Close()

	fmt.Println("Done. Result saved in BusinessCard.pdf")

	// Example 2) Replace text in a region with new text

	doc = NewPDFDoc(inputPath + "newsletter.pdf")
	doc.InitSecurityHandler()

	replacer = NewContentReplacer()
	page = doc.GetPage(1)
	replacer.AddText(page.GetMediaBox(), "hello hello hello hello hello hello hello hello hello hello")
	replacer.Process(page)

	doc.Save(outputPath + "ContentReplaced.pdf", uint(SDFDocE_linearized))
	doc.Close()

	fmt.Println("Done. Result saved in ContentReplaced.pdf")
	
    PDFNetTerminate()
	fmt.Println("Done.")
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <iostream>
#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/Image.h>
#include <PDF/ContentReplacer.h>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace std;
using namespace pdftron;
using namespace Common;
using namespace SDF;
using namespace PDF;

//-----------------------------------------------------------------------------------------
// The sample code illustrates how to use the ContentReplacer class to make using 
// 'template' pdf documents easier.
//-----------------------------------------------------------------------------------------
int main(int argc, char * argv[])
{
	int ret = 0;

	string input_path = "../../TestFiles/";
	string output_path = input_path + "Output/";

	// The first step in every application using PDFNet is to initialize the 
	// library and set the path to common PDF resources. The library is usually 
	// initialized only once, but calling Initialize() multiple times is also fine.
	PDFNet::Initialize(LicenseKey);

	//--------------------------------------------------------------------------------
	// Example 1) Update a business card template with personalized info
	try
	{
		PDFDoc doc(input_path + "BusinessCardTemplate.pdf");
		doc.InitSecurityHandler();

		// first, replace the image on the first page
		ContentReplacer replacer;
		Page page = doc.GetPage(1);
		Image img = Image::Create(doc, input_path + "peppers.jpg");
		replacer.AddImage(page.GetMediaBox(), img.GetSDFObj());
		// next, replace the text place holders on the second page
		replacer.AddString("NAME", "John Smith");
		replacer.AddString("QUALIFICATIONS", "Philosophy Doctor"); 
		replacer.AddString("JOB_TITLE", "Software Developer"); 
		replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd"); 
		replacer.AddString("ADDRESS_LINE2", "Vancouver, BC"); 
		replacer.AddString("PHONE_OFFICE", "604-730-8989"); 
		replacer.AddString("PHONE_MOBILE", "604-765-4321"); 
		replacer.AddString("EMAIL", "info@pdftron.com"); 
		replacer.AddString("WEBSITE_URL", "http://www.pdftron.com"); 
		// finally, apply
		replacer.Process(page);
		
		doc.Save(output_path + "BusinessCard.pdf", SDFDoc::e_remove_unused, 0);
		cout << "Done. Result saved in BusinessCard.pdf" << endl;
	}
	catch (Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	//--------------------------------------------------------------------------------
	// Example 2) Replace text in a region with new text
	try
	{
		PDFDoc doc(input_path + "newsletter.pdf");
		doc.InitSecurityHandler();

		ContentReplacer replacer;
		Page page = doc.GetPage(1);
		Rect target_region = page.GetMediaBox();
		UString replacement_text("hello hello hello hello hello hello hello hello hello hello");
		replacer.AddText(target_region, replacement_text);
		replacer.Process(page);

		doc.Save(output_path + "ContentReplaced.pdf", SDFDoc::e_remove_unused, 0);
		cout << "Done. Result saved in ContentReplaced.pdf" << endl;
	}
	catch (Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch (...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	cout << "Done." << endl;

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.pdf.*;
import com.pdftron.sdf.*;

public class ContentReplacerTest {

    public static void main(String[] args) {
        String input_path = "../../TestFiles/";
        String output_path = input_path + "Output/";

        // The first step in every application using PDFNet is to initialize the
        // library and set the path to common PDF resources. The library is usually
        // initialized only once, but calling Initialize() multiple times is also fine.
        PDFNet.initialize(PDFTronLicense.Key());

        //--------------------------------------------------------------------------------
        // Example 1) Update a business card template with personalized info

        try (PDFDoc doc = new PDFDoc(input_path + "BusinessCardTemplate.pdf")) {
            doc.initSecurityHandler();

            ContentReplacer replacer = new ContentReplacer();
            Page page = doc.getPage(1);
            // first, replace the image on the first page
            Image img = Image.create(doc, input_path + "peppers.jpg");
            replacer.addImage(page.getMediaBox(), img.getSDFObj());
            // next, replace the text place holders on the second page
            replacer.addString("NAME", "John Smith");
            replacer.addString("QUALIFICATIONS", "Philosophy Doctor");
            replacer.addString("JOB_TITLE", "Software Developer");
            replacer.addString("ADDRESS_LINE1", "#100 123 Software Rd");
            replacer.addString("ADDRESS_LINE2", "Vancouver, BC");
            replacer.addString("PHONE_OFFICE", "604-730-8989");
            replacer.addString("PHONE_MOBILE", "604-765-4321");
            replacer.addString("EMAIL", "info@pdftron.com");
            replacer.addString("WEBSITE_URL", "http://www.pdftron.com");
            // finally, apply
            replacer.process(page);

            doc.save(output_path + "BusinessCard.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);
            System.out.println("Done. Result saved in BusinessCard.pdf");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        //--------------------------------------------------------------------------------
        // Example 2) Replace text in a region with new text

        try (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) {
            doc.initSecurityHandler();

            ContentReplacer replacer = new ContentReplacer();
            Page page = doc.getPage(1);
            Rect target_region = page.getMediaBox();
            String replacement_text = "hello hello hello hello hello hello hello hello hello hello";
            replacer.addText(target_region, replacement_text);
            replacer.process(page);

            doc.save(output_path + "ContentReplaced.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);
            System.out.println("Done. Result saved in ContentReplaced.pdf");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        System.out.println("Done.");

        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="JavaScript" %}
{% code lineNumbers="true" %}

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------


const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {

  exports.runContentReplacer = () => {

    const main = async() => {
      const inputPath = '../TestFiles/';
      const outputPath = inputPath + 'Output/';

      try {
        const inputFilename = 'BusinessCardTemplate.pdf';
        const outputFilename = 'BusinessCard.pdf';

        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename);
        doc.initSecurityHandler();

        const replacer = await PDFNet.ContentReplacer.create();
        const page = await doc.getPage(1);
        const img = await PDFNet.Image.createFromFile(doc, inputPath + 'peppers.jpg');

        const region = await page.getMediaBox();
        const replace = await img.getSDFObj();
        await replacer.addImage(region, replace);
        await replacer.addString('NAME', 'John Smith');
        await replacer.addString('QUALIFICATIONS', 'Philosophy Doctor');
        await replacer.addString('JOB_TITLE', 'Software Developer');
        await replacer.addString('ADDRESS_LINE1', '#100 123 Software Rd');
        await replacer.addString('ADDRESS_LINE2', 'Vancouver, BC');
        await replacer.addString('PHONE_OFFICE', '604-730-8989');
        await replacer.addString('PHONE_MOBILE', '604-765-4321');
        await replacer.addString('EMAIL', 'info@pdftron.com');
        await replacer.addString('WEBSITE_URL', 'http://www.pdftron.com');
        await replacer.process(page);

        await doc.save(outputPath + outputFilename, PDFNet.SDFDoc.SaveOptions.e_remove_unused);

        console.log('Done. Result saved in ' + outputFilename);
      } catch (err) {
        console.log(err);
      }
      try {
        const inputFilename = 'newsletter.pdf';
        const outputFilename = 'ContentReplaced.pdf';

        const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + inputFilename);
        doc.initSecurityHandler();

        const replacer = await PDFNet.ContentReplacer.create();
        const page = await doc.getPage(1);
        const region = await page.getMediaBox();
        await replacer.addText(region, 'hello hello hello hello hello hello hello hello hello hello');
        await replacer.process(page);

        await doc.save(outputPath + outputFilename, PDFNet.SDFDoc.SaveOptions.e_remove_unused);

        console.log('Done. Result saved in ' + outputFilename);
      } catch (err) {
        console.log(err);
      }
      console.log('Done.');
    };
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error){console.log('Error: ' + JSON.stringify(error));}).then(function(){return PDFNet.shutdown();});
  };
  exports.runContentReplacer();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=ContentReplacerTest.js
```

{% endcode %}
{% endtab %}

{% tab title="Python" %}
{% code lineNumbers="true" %}

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

# Relattive path to the folder containing the test files.
input_path = "../../TestFiles/"
output_path = "../../TestFiles/Output/"            

#-----------------------------------------------------------------------------------------
# The sample code illustrates how to use the ContentReplacer class to make using 
# 'template' pdf documents easier.
#-----------------------------------------------------------------------------------------
def main():
	PDFNet.Initialize(LicenseKey)

	# Example 1) Update a business card template with personalized info

	doc = PDFDoc(input_path + "BusinessCardTemplate.pdf")
	doc.InitSecurityHandler()

	# first, replace the image on the first page
	replacer = ContentReplacer()
	page = doc.GetPage(1)
	img = Image.Create(doc.GetSDFDoc(), input_path + "peppers.jpg")
	replacer.AddImage(page.GetMediaBox(), img.GetSDFObj())
	# next, replace the text place holders on the second page
	replacer.AddString("NAME", "John Smith")
	replacer.AddString("QUALIFICATIONS", "Philosophy Doctor")
	replacer.AddString("JOB_TITLE", "Software Developer")
	replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd")
	replacer.AddString("ADDRESS_LINE2", "Vancouver, BC")
	replacer.AddString("PHONE_OFFICE", "604-730-8989")
	replacer.AddString("PHONE_MOBILE", "604-765-4321") 
	replacer.AddString("EMAIL", "info@pdftron.com")
	replacer.AddString("WEBSITE_URL", "http://www.pdftron.com")
	# finally, apply
	replacer.Process(page)

	doc.Save(output_path + "BusinessCard.pdf", SDFDoc.e_linearized)
	doc.Close()

	print("Done. Result saved in BusinessCard.pdf")

	# Example 2) Replace text in a region with new text

	doc = PDFDoc(input_path + "newsletter.pdf")
	doc.InitSecurityHandler()

	replacer = ContentReplacer()
	page = doc.GetPage(1)
	replacer.AddText(page.GetMediaBox(), "hello hello hello hello hello hello hello hello hello hello")
	replacer.Process(page)

	doc.Save(output_path + "ContentReplaced.pdf", SDFDoc.e_linearized)
	doc.Close()

	print("Done. Result saved in ContentReplaced.pdf")
	PDFNet.Terminate()
	print("Done.")

if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

{% tab title="PHP" %}
{% code lineNumbers="true" %}

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))

include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

//-----------------------------------------------------------------------------------------
// The sample code illustrates how to use the ContentReplacer class to make using 
// 'template' pdf documents easier.
//-----------------------------------------------------------------------------------------
	PDFNet::Initialize($LicenseKey);
	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
	
	// Relative path to the folder containing the test files.
	$input_path = getcwd()."/../../TestFiles/";
	$output_path = $input_path."Output/";

	//--------------------------------------------------------------------------------
	// Example 1) Update a business card template with personalized info
	$doc = new PDFDoc($input_path."BusinessCardTemplate.pdf");
	$doc->InitSecurityHandler();

	// first, replace the image on the first page
	$replacer = new ContentReplacer();
	$page = $doc->GetPage(1);
	$img = Image::Create($doc->GetSDFDoc(), $input_path."peppers.jpg");
	$replacer->AddImage($page->GetMediaBox(), $img->GetSDFObj());
	// next, replace the text place holders on the second page
	$replacer->AddString("NAME", "John Smith");
	$replacer->AddString("QUALIFICATIONS", "Philosophy Doctor"); 
	$replacer->AddString("JOB_TITLE", "Software Developer"); 
	$replacer->AddString("ADDRESS_LINE1", "#100 123 Software Rd"); 
	$replacer->AddString("ADDRESS_LINE2", "Vancouver, BC"); 
	$replacer->AddString("PHONE_OFFICE", "604-730-8989"); 
	$replacer->AddString("PHONE_MOBILE", "604-765-4321"); 
	$replacer->AddString("EMAIL", "info@pdftron.com"); 
	$replacer->AddString("WEBSITE_URL", "http://www.pdftron.com"); 
	// finally, apply
	$replacer->Process($page);
	
	$doc->Save($output_path."BusinessCard.pdf", 0);
	echo nl2br("Done. Result saved in BusinessCard.pdf\n");

	//--------------------------------------------------------------------------------
	// Example 2) Replace text in a region with new text
	$doc = new PDFDoc($input_path."newsletter.pdf");
	$doc->InitSecurityHandler();

	$replacer = new ContentReplacer();
	$page = $doc->GetPage(1);
	$target_region = $page->GetMediaBox();
	$replacer->AddText($target_region, "hello hello hello hello hello hello hello hello hello hello");
	$replacer->Process($page);

	$doc->Save($output_path."ContentReplaced.pdf", 0);
	echo nl2br("Done. Result saved in ContentReplaced.pdf\n");
	PDFNet::Terminate();
	echo nl2br("Done.\n");
?>
```

{% endcode %}
{% endtab %}

{% tab title="Ruby" %}
{% code lineNumbers="true" %}

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#-----------------------------------------------------------------------------------------
# The sample code illustrates how to read and edit existing outline items and create 
# new bookmarks using the high-level API.
#-----------------------------------------------------------------------------------------

# Relative path to the folder containing the test files.
input_path = "../../TestFiles/"
output_path = "../../TestFiles/Output/"

#-----------------------------------------------------------------------------------------
# The sample code illustrates how to use the ContentReplacer class to make using 
# 'template' pdf documents easier.
#-----------------------------------------------------------------------------------------
	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Example 1) Update a business card template with personalized info
	
	doc = PDFDoc.new(input_path + "BusinessCardTemplate.pdf")
	doc.InitSecurityHandler()
	
	# first, replace the image on the first page
	replacer = ContentReplacer.new()
	page = doc.GetPage(1)
	img = Image.Create(doc.GetSDFDoc(), input_path + "peppers.jpg")
	replacer.AddImage(page.GetMediaBox(), img.GetSDFObj())
	# next, replace the text place holders on the second page
	replacer.AddString("NAME", "John Smith")
	replacer.AddString("QUALIFICATIONS", "Philosophy Doctor")
	replacer.AddString("JOB_TITLE", "Software Developer")
	replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd")
	replacer.AddString("ADDRESS_LINE2", "Vancouver, BC")
	replacer.AddString("PHONE_OFFICE", "604-730-8989")
	replacer.AddString("PHONE_MOBILE", "604-765-4321")
	replacer.AddString("EMAIL", "info@pdftron.com")
	replacer.AddString("WEBSITE_URL", "http://www.pdftron.com")
	# finally, apply
	replacer.Process(page)
	
	doc.Save(output_path + "BusinessCard.pdf", 0)
	doc.Close()
	puts "Done. Result saved in BusinessCard.pdf"

	# Example 2) Replace text in a region with new text
	
	doc = PDFDoc.new(input_path + "newsletter.pdf")
	doc.InitSecurityHandler()
	
	replacer = ContentReplacer.new()
	page = doc.GetPage(1)
	replacer.AddText(page.GetMediaBox(), "hello hello hello hello hello hello hello hello hello hello")
	replacer.Process(page)
	
	doc.Save(output_path + "ContentReplaced.pdf", SDFDoc::E_linearized)
	doc.Close()
	puts "Done. Result saved in ContentReplaced.pdf"
	PDFNet.Terminate
	puts "Done."
```

{% endcode %}
{% endtab %}

{% tab title="VB" %}
{% code lineNumbers="true" %}

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System

Imports pdftron
Imports pdftron.Common
Imports pdftron.Filters
Imports pdftron.SDF
Imports pdftron.PDF

Module ContentReplacerTestVB
	Dim pdfNetLoader As PDFNetLoader
	Sub New()
		pdfNetLoader = pdftron.PDFNetLoader.Instance()
	End Sub
'-----------------------------------------------------------------------------------------
' The sample code illustrates how to use the ContentReplacer class to make using 
' 'template' pdf documents easier.
'-----------------------------------------------------------------------------------------

	Sub Main()


		PDFNet.Initialize(PDFTronLicense.Key)

		' Relative path to the folder containing test files.
		Dim input_path As String = "../../../../TestFiles/"
		Dim output_path As String = "../../../../TestFiles/Output/"


		' Example 1) Update a business card template with personalized info
		Try
			Using doc As PDFDoc = New PDFDoc(input_path + "BusinessCardTemplate.pdf")
				doc.InitSecurityHandler()

				' first, replace the image on the first page
				Using replacer As ContentReplacer = New ContentReplacer()
					Dim page As Page = doc.GetPage(1)
					Dim img As Image = Image.Create(doc.GetSDFDoc(), input_path + "peppers.jpg")
					replacer.AddImage(page.GetMediaBox(), img.GetSDFObj())
					' next, replace the text place holders on the second page
					replacer.AddString("NAME", "John Smith")
					replacer.AddString("QUALIFICATIONS", "Philosophy Doctor")
					replacer.AddString("JOB_TITLE", "Software Developer")
					replacer.AddString("ADDRESS_LINE1", "#100 123 Software Rd")
					replacer.AddString("ADDRESS_LINE2", "Vancouver, BC")
					replacer.AddString("PHONE_OFFICE", "604-730-8989")
					replacer.AddString("PHONE_MOBILE", "604-765-4321")
					replacer.AddString("EMAIL", "info@pdftron.com")
					replacer.AddString("WEBSITE_URL", "http://www.pdftron.com")
					' finally, apply
					replacer.Process(page)
				End Using

				doc.Save(output_path + "BusinessCard.pdf", 0)
			End Using
			Console.WriteLine("Done. Result saved in BusinessCard.pdf")
		Catch e As PDFNetException
			Console.WriteLine(e.Message)
		End Try

		' Example 2) Replace text in a region with new text
		Try
			Using doc1 As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
				doc1.InitSecurityHandler()

				Dim replacer1 As ContentReplacer = New ContentReplacer()
				Dim page1 As Page = doc1.GetPage(1)
				replacer1.AddText(page1.GetMediaBox(), "hello hello hello hello hello hello hello hello hello hello")
				replacer1.Process(page1)

				doc1.Save(output_path + "ContentReplaced.pdf", SDFDoc.SaveOptions.e_linearized)
			End Using
			Console.WriteLine("Done. Result saved in ContentReplaced.pdf")
		Catch e As PDFNetException
			Console.WriteLine(e.Message)
		End Try
		PDFNet.Terminate()
		Console.WriteLine("Done.")
	End Sub

End Module
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/core/get-started/samples/contentreplacertest.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
