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

//---------------------------------------------------------------------------------------
// The following sample illustrates how to find and replace text in a document
//---------------------------------------------------------------------------------------

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

((exports) => {

	exports.runFindReplace = () => {

		const main = async () => {
			// Relative path to the folder containing test files.
			const inputPath = '../TestFiles/';
			const outputPath = inputPath + 'Output/';

			try {
				// start stack-based deallocation with startDeallocateStack. Later on when endDeallocateStack is called,
				// all objects in memory that were initialized since the most recent startDeallocateStack call will be
				// cleaned up. Doing this makes sure that memory growth does not get too high.
				await PDFNet.startDeallocateStack();

				// Open a PDF document to edit
				const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'find-replace-test.pdf');

				const options = await PDFNet.FindReplace.createFindReplaceOptions();

				// Set some find/replace options
				options.setWholeWords(true);
				options.setMatchCase(true);
				options.setMatchMode(PDFNet.FindReplace.FindReplaceOptions.MatchType.e_exact);
				options.setReflowMode(PDFNet.FindReplace.FindReplaceOptions.ReflowType.e_para);
				options.setAlignment(PDFNet.FindReplace.FindReplaceOptions.HorizAlignment.e_left);

				// Perform a Find/Replace finding "the" with "THE INCREDIBLE"
				await PDFNet.FindReplace.findReplaceText(doc, "the", "THE INCREDIBLE", options);

				// Save the edited PDF
				await doc.save(outputPath + 'find-replace-test-replaced.pdf', PDFNet.SDFDoc.SaveOptions.e_linearized);

				await PDFNet.endDeallocateStack();
			} catch (err) {
				console.log(err.stack);
			}
		};
		PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function (error) { console.log('Error: ' + JSON.stringify(error)); }).then(function () { return PDFNet.shutdown(); });
	};
	exports.runFindReplace();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=FindReplaceTest.js