Changing text in PDF
Use the Automation API to find and replace text in a PDF document from an external interface — enter a search term, specify replacement text, and apply changes across all pages.
The document opens as a PDF. Your code calls connector.callCommand() to execute Document Builder API methods that recognize page content, iterate through text objects, and replace matching text.
How it works
-
When the user enters a search term and replacement text, then clicks Replace all, the
connector.callCommand()method is used to execute Document Builder API code inside the editor. The code iterates through all pages using GetPagesCount and GetPage, and calls RecognizeContent on each page to get all drawing objects. For each shape, it retrieves the inner content with GetContent, iterates through paragraphs using GetElementsCount and GetElement, reads text with GetText, and replaces it with SetText:Asc.scope.replaceParams = { findText, replaceWith, matchCase };connector.callCommand(() => {const params = Asc.scope.replaceParams;const regex = new RegExp(params.findText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),params.matchCase ? "g" : "gi",);const doc = Api.GetDocument();const pageCount = doc.GetPagesCount();const results = [];for (let i = 0; i < pageCount; i++) {const page = doc.GetPage(i);const drawings = page.RecognizeContent();let pageReplacements = 0;for (let d = 0; d < drawings.length; d++) {const drawing = drawings[d];if (drawing.GetClassType() === "shape") {const content = drawing.GetContent();const elemCount = content.GetElementsCount();for (let e = 0; e < elemCount; e++) {const elem = content.GetElement(e);if (elem.GetClassType() === "paragraph") {const text = elem.GetText();const matches = text.match(regex);if (matches) {elem.SetText(text.replace(regex, params.replaceWith));pageReplacements += matches.length;}}}}}if (pageReplacements > 0) {results.push({ pageIndex: i, count: pageReplacements });}}return results;}, (results) => {// Display the replacement results in the external panel}); -
The external panel displays the number of replacements per page. Each result shows how many occurrences were replaced and on which page they were found.
Please note that the connector is available only for ONLYOFFICE Docs Developer.
The connector is a premium feature available at an extra cost. See ONLYOFFICE Docs Developer for pricing details, or contact our sales team at sales@onlyoffice.com to request a quote.