Convert RTF to PDF and HTML with JavaScript in React

Convert RTF to PDF and HTML with JavaScript in React

2025-01-10 01:02:37 Written by  Administrator
Rate this item
(0 votes)

RTF files are versatile, containing text, images, and formatting information. Converting these files into PDF and HTML ensures that they are accessible and display consistently across various devices and browsers. Whether you're building a document viewer or integrating document management features into your application, mastering RTF conversion is a valuable skill.

In this article, you will learn how to convert RTF to PDF and RTF to HTML in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with converting RTF to PDF and HTML in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:

Copy
npm i spire.office

The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.

For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project

Convert RTF to PDF with JavaScript

With Spire.Doc for JavaScript, converting RTF files to PDF is straightforward. Utilize the Document.LoadFromFile() method to load the RTF file, preserving its formatting. Then, save it as a PDF using the Document.SaveToFile() method. This process ensures high-quality output, making file format conversion easy and efficient.

Here are the steps to convert RTF to PDF in React using Spire.Doc for JavaScript:

  • Load the font files used in the RTF document into the virtual file system (VFS).
  • Create a new Document object using the new wasmModule.Document() method.
  • Load the input RTF file using the Document.LoadFromFile() method.
  • Save the document as a PDF file using the Document.SaveToFile() method.
  • Generate a Blob from the PDF file, create a download link, and trigger the download.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.doc.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert RTF to PDF
  const convertRtfToPdf = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name 
      const inputFileName = 'input.rtf';

      // Fetch the input file and add it to the VFS
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an instance of the Document class
      const doc = new wasmModule.Document();

      // Load the RTF file
      doc.LoadFromFile(inputFileName);

      // Define the output file name
      const outputFileName = "RtfToPdf.pdf";

      // Save the document to the specified path
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF });

      // Read the generated PDF file from VFS
      const modifiedFileArray =window.dotnetRuntime.Module.FS.readFile(outputFileName);

      // Create a Blob object from the PDF file
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      // Clean up resources
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert RTF to PDF in React</h1>
      <button onClick={convertRtfToPdf} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}
export default App;

Run the code to launch the React app at localhost:3000. Click "Convert," and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

React app runs at localhost:3000

Below is a screenshot of the generated PDF document:

Convert RTF to PDF in React

Convert RTF to HTML with JavaScript

When converting RTF to HTML, it's crucial to decide whether to embed image files and CSS stylesheets as internal resources, as these elements significantly impact the HTML file's display.

With Spire.Doc for JavaScript, you can easily configure these settings using the Document.HtmlExportOptions.CssStyleSheetType and Document.HtmlExportOptions.ImageEmbedded properties.

Here are the steps to convert RTF to HTML with embedded images and CSS stylesheets using Spire.Doc for JavaScript:

  • Load the font files used in the RTF document into the virtual file system (VFS).
  • Create a new Document object using the new wasmModule.Document() method.
  • Load the input RTF file using the Document.LoadFromFile() method.
  • Embed CSS stylesheet in the HTML file by setting the Document.HtmlExportOptions.CssStyleSheetType as Internal.
  • Embed image files in the HTML file by setting the Document.HtmlExportOptions.ImageEmbedded to true.
  • Save the document as an HTML file using the Document.SaveToFile() method.
  • Generate a Blob from the PDF file, create a download link, and trigger the download.
  • JavaScript
Copy
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.Doc
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
        const rawModule = spireModule.default || spireModule;
        window.wasmModule = typeof rawModule === 'function'
          ? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
          : rawModule;
        setWasmModule(window.wasmModule);
      } catch (error) {
        console.error('Failed to load spire.doc.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert RTF to HTML
  const convertRtfToHtml = async () => {
    const wasmModule = window.wasmModule.spiredoc;

    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
      await window.spire.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify the input file name 
      const inputFileName = 'input.rtf';

      // Fetch the input file and add it to the VFS
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create an instance of the Document class
      const doc = new wasmModule.Document();

      // Load the RTF file
      doc.LoadFromFile(inputFileName);

      // Embed CSS file in the HTML file      
      doc.HtmlExportOptions.CssStyleSheetType = wasmModule.CssStyleSheetType.Internal;     

      // Embed images in the HTML file      
      doc.HtmlExportOptions.ImageEmbedded = true;

      // Define the output file name
      const outputFileName = "RtfToHtml.html";

      // Save the document to the specified path
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Html});
 
      // Read the generated HTML file from VFS
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);

      // Create a Blob object from the HTML file
      const modifiedFile = new Blob([modifiedFileArray], { type: 'text/html'});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert RTF to HTML in React</h1>
      <button onClick={convertRtfToHtml} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert RTF to HTML in React

Get a Free License

To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.

Additional Info

  • tutorial_title:
Last modified on Friday, 05 June 2026 09:22