Products Technologies Demo Docs Blog Support Company

Replace Words at the Input Position with Formatted Content from a Web API

Writing assistance and placeholder replacement are advanced features that help users create professional documents. This sample shows how to replace the word at the current input position with content retrieved from a Web API.

Replace Words at the Input Position with Formatted Content from a Web API

Writing assistance features significantly speed up the writing process by providing auto-correction, auto-completion, and key phrase replacement, saving time and reducing errors to create a professional document or letter. In particular, pre-designed and phrased sentences that are inserted frequently improve the user experience of such applications.

This sample shows how to replace the word at the current input position with content retrieved from a Web API.

Web API

To simulate the phrase replacement, the following Web API method ReplaceWord accepts a string and returns a value from a dictionary:

[HttpGet]
public IActionResult ReplaceWord(string word) {

  Dictionary<string, string> dict = new Dictionary<string, string>()
  {
     { "Word1", "<strong>Formatted</strong> replacement for <em>Word1</em>" },
     { "Word2", "<strong>Formatted</strong> replacement for <em>Word2</em>" },
     { "Word3", "<strong>Formatted</strong> replacement for <em>Word3</em>" }
  };

  return dict.ContainsKey(word) ? Ok(dict[word]) : Ok(null);
}

This Web API method is called from JavaScript in the asynchronous method replaceWord:

function replaceWord(word) {
  return new Promise(resolve => {
    $.get("home/replaceWord", { word: word })
      .done(data => resolve(data))
      .fail(() => resolve(null));
  });
}

Replacing the Selection

When the user presses F8, the word at the input position is selected and retrieved. This word is then sent to the Web API to retrieve the replacement string. This string will eventually be loaded into the selection to replace the current string.

TXTextControl.addEventListener("textControlLoaded", async function () {
    document.addEventListener("keydown", logKey);

    async function logKey(e) {
        if (e.key === "F8") {
            const text = await getTextFromSelection();
            const replacedText = await replaceWord(text);

            if (replacedText !== undefined) {
                await loadReplacedText(replacedText);
            }
        }
    }

    function getTextFromSelection() {
        return new Promise(resolve => {
            TXTextControl.selectWord(() => {
                TXTextControl.selection.getText(text => resolve(text));
            });
        });
    }

    async function loadReplacedText(replacedText) {
        const encodedText = btoa(replacedText);
        await TXTextControl.selection.load(TXTextControl.StreamType.HTMLFormat, encodedText);
    }
});

The following screen video shows the replacement in action.

Phrase replacement

You can test this yourself by downloading the Visual Studio project from our GitHub repository.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

GitHub

Download and Fork This Sample on GitHub

We proudly host our sample code on github.com/TextControl.

Please fork and contribute.

Download ZIP

Open on GitHub

Open in Visual Studio

Requirements for this sample

  • Visual Studio 2022
  • TX Text Control .NET Server 31.0

ASP.NET

Integrate document processing into your applications to create documents such as PDFs and MS Word documents, including client-side document editing, viewing, and electronic signatures.

ASP.NET Core
Angular
Blazor
JavaScript
React
  • Angular
  • Blazor
  • React
  • JavaScript
  • ASP.NET MVC, ASP.NET Core, and WebForms

Learn more Trial token Download trial

Related Posts

ASP.NETASP.NET CoreElectronic Signatures

Preparing Documents for Electronic Signatures using MailMerge in C#

There are many benefits to using MS Word compatible templates to prepare documents for electronic signature capture. This article shows how to use MailMerge to prepare documents for the signing…


ASP.NETASP.NET CorePDF

Using QR Codes in PDF Documents in C# .NET

QR codes are a powerful tool for embedding machine-readable information in documents. In this article, we will explore how to generate and insert them into PDF documents using C# .NET with TX Text…


ASP.NETASP.NET CoreE-Invoicing

Why Structured E-Invoices Still Need Tamper Protection using C# and .NET

ZUGFeRD, Factur-X, German e-invoicing rules, and how to seal PDF invoices with TX Text Control to prevent tampering. Learn how to create compliant e-invoices with C# and .NET.


ASP.NETASP.NET CoreForms

Create Fillable PDFs from HTML Forms in C# ASP.NET Core Using a WYSIWYG Template

Learn how to generate PDFs from HTML forms in ASP.NET Core using a pixel-perfect WYSIWYG template. Extract form fields from a document, render a dynamic HTML form, and merge the data server-side…


ASP.NETASP.NET CoreHTML

Why HTML to PDF Conversion is Often the Wrong Choice for Business Documents…

In this article, we explore the challenges of HTML to PDF conversion for business documents in C# .NET and present alternative solutions that offer better performance and reliability. Discover why…

Share on this blog post on: