Simple Search and Replace

This guide will show you how to do a basic text search and replace in PDF document.

Sample Input

page that contains the search term

Before you begin

Get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git 

Navigate to the text folder in the unipdf-examples directory.

cd unipdf-examples/text

How it works

Lines 10-21 import the UniPDF packages and other required dependecies.

The init function in lines 23-30 authenticates your request using your UNIDOC_LICENSE_API_KEY.

The main function in lines 32-48 validates your input and passes them as arguments to the searchReplace function.

Lines 50-95 define the searchReplace function, which will read the PDF document then pass each pages into searchReplacePageText function to be processed and write the result back into output PDF document.

Lines 97-160 define the searchReplacePageText function, which will read and parse the page’s content stream to look for the required search text and replace it with the supplied replacement text.

Run the code

Run this command to search and replace specific text in PDF document. This will also get all the required dependencies to run the program.

go run pdf_search_replace.go input.pdf output.pdf "search text" "replacement text"

# to reproduce sample output
go run pdf_search_replace.go input.pdf output.pdf "Example" "Annual"

Sample output

You will see the replaced text on the output PDF.

page with replaced text

Got any Questions?

We're here to help you.