Replace

This guide will show you how to do text replacement using UniPDF library.

Before you begin

Before starting to follow along with this guide you should 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.

Project setup

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 search-and-replace folder in the unipdf-examples directory.

cd unipdf-examples/search-and-replace

Configure environment variables

Replace the UNIDOC_LICENSE_API_KEY with your API credentials from your UniCloud account.

Linux/Mac

export UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

Windows

set UNIDOC_LICENSE_API_KEY=PUT_YOUR_API_KEY_HERE

How it works

The import section in lines 10-19 imports necessary libraries.

The init function defined in lines 21-28 authenticates your library request by setting a metered API key. If the API key is missing or invalid, the program will terminate with an error.

The main function defined in lines 30-76 performs the main operations of finding and replacing text in a PDF file. This function starts by parsing the command line arguments and setting the input parameters in lines 32-54. These parameter are:

Pattern: The text to search for.
replacement: The text to replace the pattern with.
filePath: The path to the input PDF file.
outputPath: The path to save the modified PDF.

Then a PDF reader to read the content of the PdF file is created in line 56 using model.NewPdfReaderFromFile. The extractor.Editor object that is used for text replacement is initialized in line 61. Line 63 performs the replacement operation using editor.Replace method by providing the necessary parameters. The text matched by pattern is replaced with given replacement on the specified pages. If the operation fails, an error message is printed, and the program exits.

Line 69 saves the modified PDF to the specified outputPath using editor.WriteToFile. If saving fails, an error message is displayed, and the program exits. Line 75 prints a confirmation message indicating the replacement was successful.

Run the code

Run the code using the following command

go run replace_text.go <pattern> <replacement> <pages> <input> <output>

Example usage:

go run replace_text.go "Australia" "America" "1,2" ./test-data/file1.pdf ./test-data/result.pdf

Sample output

Finished replacing Australia by America and saved the output file at ./test-data/file1.pdf

Got any Questions?

We're here to help you.