Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

Browser-Side Word-to-RTF Conversion with JavaScript

In many business scenarios, Word documents (DOCX) need to be exported as RTF. RTF is a cross-platform rich text format with strong compatibility, and many legacy systems, desktop editors, and content-import interfaces su

In many business scenarios, Word documents (DOCX) need to be exported as RTF. RTF is a cross-platform rich text format with strong compatibility, and many legacy systems, desktop editors, and content-import interfaces support RTF as a preferred format. Conventional solutions usually upload the file to a backend service for conversion. However, when requirements include offline operation, pure frontend processing, and avoiding file uploads, you can use document processing capabilities compiled to WASM to perform parsing and export directly in browser memory.

The solution below runs entirely in the browser. By loading a WASM module, it performs document loading, prepares rendering dependencies, and exports the document through a frontend virtual file system. The generated RTF file is then offered to the user for download. The example is implemented as a React component.

Dependency note: This example uses Spire.Doc for JavaScript, which compiles document processing logic to WebAssembly and runs it in the browser.

Process Overview

The conversion pipeline consists of the following steps:

  1. Wait for the WASM module to finish initializing and obtain the document operation entry point.
  2. Fetch font resources and the source Word file into the WASM virtual file system (VFS).
  3. Load the DOCX document from the VFS.
  4. Specify the output format and call the save API to generate RTF.
  5. Read the binary content from the VFS, wrap it in a Blob, and trigger a browser download.
  6. Release the document object to avoid memory leaks.

Complete Code Example

function App() {
  const wordToRtf = async () => {
    // Get the initialized WASM module instance
    const docModule = window.wasmModule?.spiredoc;

    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load font files and the source document into the WASM virtual file system
    await window.spire.FetchFileToVFS(
      'arial.ttf',
      '/Library/Fonts/',
      `${process.env.PUBLIC_URL}/font/`
    );
    await window.spire.FetchFileToVFS(
      'arialbd.ttf',
      '/Library/Fonts/',
      `${process.env.PUBLIC_URL}/font/`
    );
    await window.spire.FetchFileToVFS(
      'WordToRtf.docx',
      '',
      `${process.env.PUBLIC_URL}/data/`
    );

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile('WordToRtf.docx');

    // Export as RTF
    const outputFileName = 'WordToRtf.rtf';
    doc.SaveToFile({
      fileName: outputFileName,
      fileFormat: docModule.FileFormat.Rtf
    });
    doc.Dispose();

    // Read the generated file as binary data from the WASM VFS
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'application/rtf' });
    const url = URL.createObjectURL(blob);

    // Create a temporary <a> element to trigger the download
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();

    // Release the object URL and reclaim memory
    URL.revokeObjectURL(url);
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Word to RTF</h1>
      <button onClick={wordToRtf}>Generate</button>
    </div>
  );
}

export default App;

Key Implementation Details

1. Checking Module Readiness

WASM files are relatively large and require time to load and initialize. The code checks whether the module is ready through window.wasmModule?.spiredoc. In a production project, it is better to provide loading states and progress indicators instead of a simple alert, so users understand what is happening.

2. Virtual File System (VFS)

The WASM runtime does not have access to the browser's native file system, so the library implements an internal virtual file system. FetchFileToVFS fetches static resources, such as fonts and documents, from the frontend static resource directory and writes them into the VFS for the document engine to read.

The key consideration here is font resources. If fonts used by the document are missing, text layout and styling may be corrupted after conversion. The example preloads Arial regular and bold fonts. You can extend this list based on the fonts used by your business documents.

Path parameters:

  • First parameter: resource file name.
  • Second parameter: target path in the VFS.
  • Third parameter: base URL for frontend static resources. The example uses PUBLIC_URL, which follows React static asset deployment conventions.

3. Document Loading and Format Export

const doc = new docModule.Document();
doc.LoadFromFile('WordToRtf.docx');
doc.SaveToFile({
  fileName: outputFileName,
  fileFormat: docModule.FileFormat.Rtf
});

This is the core of the conversion. The engine reads the DOCX file from the VFS and outputs it according to the specified FileFormat.Rtf enum. Other supported formats, such as PDF and HTML, can be selected through similar enum values.

Important: Call Dispose() after conversion. WASM objects are not automatically reclaimed by JavaScript garbage collection, so document instances must be released manually. In long-running or repeated conversion scenarios, omitting this step can cause continuous memory usage, page lag, or even crashes.

4. File Reading and Browser Download

After conversion, the generated file remains in the WASM VFS and cannot be accessed directly by the browser. Use FS.readFile to read the binary byte array, wrap it in a Blob, and trigger the download through URL.createObjectURL and a temporary <a> element.

Finally, call URL.revokeObjectURL to release the memory reference.

Deployment and Resource Preparation

Place the required resources in the project's static directory in advance:

public/
├── font/
│   ├── arial.ttf
│   └── arialbd.ttf
└── data/
    └── WordToRtf.docx

If users upload custom files instead of using a fixed template, adjust the logic accordingly: read the uploaded File object and write its bytes into the VFS rather than fetching static files through FetchFileToVFS. This supports dynamic upload-and-convert workflows.

Conclusion

With a WASM-based document library, DOCX-to-RTF conversion can be completed entirely in the browser without routing files through a backend. This approach is well suited to scenarios that require data isolation or offline availability. The core idea is to use a virtual file system to provide WASM with file access capabilities, load the required fonts and source document, call the export API, and then read the binary result from the VFS and deliver it to the user.

The same pattern can be adapted to other document format conversion scenarios by changing the loading logic, the output format enum, and the corresponding resource dependencies.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.