Find and Replace in PDF

Sample code for using the Apryse SDK to perform in-place Find and Replace while preserving document layout and formatting. Sample code provided in Python, C++, C#, Java, and Objective-C.

Learn more about our Server SDK.

1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2025 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5#include <PDF/PDFNet.h>
6#include <PDF/PDFDoc.h>
7#include <PDF/PageSet.h>
8#include <Filters/MappedFile.h>
9#include <Filters/FilterReader.h>
10#include <Filters/FilterWriter.h>
11#include <PDF/ElementWriter.h>
12#include <PDF/ElementReader.h>
13#include <PDF/FindReplace.h>
14#include <PDF/FindReplaceOptions.h>
15
16#include <iostream>
17#include <fstream>
18#include "../../LicenseKey/CPP/LicenseKey.h"
19
20using namespace std;
21using namespace pdftron;
22using namespace SDF;
23using namespace PDF;
24using namespace Filters;
25
26int main(int argc, char *argv[])
27{
28 int ret = 0;
29 PDFNet::Initialize(LicenseKey);
30
31 // Relative path to the folder containing test files.
32 string input_path = "../../TestFiles/";
33 string output_path = "../../TestFiles/Output/";
34
35 // The following sample illustrates how to find and replace text in a document
36 try
37 {
38 // Open a PDF document to edit
39 PDFDoc doc(input_path + "find-replace-test.pdf");
40 FindReplaceOptions options = FindReplaceOptions();
41
42 // Set some find/replace options
43 options.SetWholeWords(true);
44 options.SetMatchCase(true);
45 options.SetMatchMode(FindReplaceOptions::e_exact);
46 options.SetReflowMode(FindReplaceOptions::e_para);
47 options.SetAlignment(FindReplaceOptions::e_left);
48
49 // Perform a Find/Replace finding "the" with "THE INCREDIBLE"
50 FindReplace::FindReplaceText(doc, "the", "THE INCREDIBLE", options);
51
52 // Save the edited PDF
53 doc.Save(output_path + "find-replace-test-replaced.pdf", SDFDoc::e_linearized);
54 }
55 catch(Common::Exception& e)
56 {
57 cout << e << endl;
58 ret = 1;
59 }
60 catch(...)
61 {
62 cout << "Unknown Exception" << endl;
63 ret = 1;
64 }
65
66 PDFNet::Terminate();
67 return ret;
68}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales