Spire.Office Knowledgebase Page 21 | E-iceblue

Python: Edit Excel Documents

2025-01-14 01:06:55 Written by Koohji

Editing an Excel document involves a variety of actions, such as inputting and formatting text, applying formulas, generating visualizations, and organizing data for clarity and insight. Being able to edit Excel documents programmatically is a crucial skill that empowers developers to enhance their data management capabilities.

In this article, you will learn how to edit an existing Excel document in Python using Spire.XLS for Python.

Install Spire.XLS for Python

This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.XLS

If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows

Read and Write Excel Files in Python

A key task when handling Excel files in Python is the efficient reading and writing of data, which is essential for numerous applications such as data analysis and report generation. Spire.XLS for Python simplifies this process by offering the CellRange.Value property. This feature allows developers to easily retrieve values from individual cells and reassign them as needed.

Here are the steps to read and write an Excel file using Python:

  • Create a Workbook object.
  • Load an Excel file from a given file path.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Get a specific cell using the Worksheet.Range property
  • Get or set the cell value using the CellRange.Value property.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Get a specific cell
cell = worksheet.Range["A1"]

# Read the cell value
cellValue = cell.Value

# Determine if the cell value is "Department"
if (cellValue  == "Department"):

    # Update the cell value
    cell.Value = "Dept."

# Save the workbook to a different
workbook.SaveToFile("ModifyExcel.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Update Excel in Python

Apply Formatting to Excel Cells in Python

Formatting Excel documents is essential for producing professional-looking reports that effectively communicate information. Spire.XLS for Python offers a comprehensive suite of APIs within the CellRange class, empowering developers to manage various formatting options seamlessly. This includes adjusting font styles, selecting cell colors, aligning text, and modifying row heights and column widths.

Here are the steps to apply styles and formats to Excel cells using Python:

  • Create a Workbook object.
  • Load an Excel file from a given file path.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Get all located range using the Worksheet.AllocatedRange property.
  • Get a specific row using the CellRange.Rows[index] property, and set the cell color, text color, text alignment, and row height using the properties under the CellRange object.
  • Get a specific column using the CellRange.Columns[index] property, and set the column width using the ColumnWidth property under the CellRange object.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Get all located range from the worksheet
allocatedRange = worksheet.AllocatedRange 

#Iterate through the rows
for rowNum in range(0, allocatedRange.RowCount):
    if rowNum == 0:
                    
        # Apply cell color to the header row
        allocatedRange.Rows[rowNum].Style.Color = Color.get_Black()

        # Change the font color of the header row
        allocatedRange.Rows[rowNum].Style.Font.Color = Color.get_White()
    else:       
        # Apply alternate colors to other rows
        if rowNum % 2 == 1:
            allocatedRange.Rows[rowNum].Style.Color = Color.get_LightGray()
        else:
            allocatedRange.Rows[rowNum].Style.Color = Color.get_White()

    # Align text to center
    allocatedRange.Rows[rowNum].HorizontalAlignment = HorizontalAlignType.Center
    allocatedRange.Rows[rowNum].VerticalAlignment = VerticalAlignType.Center 

    # Set the row height
    allocatedRange.Rows[rowNum].RowHeight = 20

# Iterate through the columns
for columnNum in range(0, allocatedRange.ColumnCount):
    if (columnNum > 0):

        # Set the column width
        allocatedRange.Columns[columnNum].ColumnWidth = 10

# Save the workbook to a different
workbook.SaveToFile("FormatExcel.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Format Excel Cells in Python

Find and Replace Text in Excel in Python

The find and replace functionality in Excel enables users to swiftly locate specific text within their spreadsheets and substitute it with new content, which is particularly useful for data corrections and updates. With Spire.XLS for Python, you can efficiently locate a cell containing a specific string using the Worksheet.FindString() method. Once identified, you can easily replace its value using the CellRange.Value property.

Here are the steps to find and replace text in Excel using Python:

  • Create a Workbook object.
  • Load an Excel file from a given file path.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Find the cell that contains a specified string using the Worksheet.FindString() method.
  • Update the cell value using the CellRange.Value property.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Define a list of department names for replacement
departments = ["Sales", "Marketing", "R&D", "HR", "IT", "Finance", "Support"]

# Define a list of placeholders that will be replaced in the Excel sheet
placeholders = ["#dept_one", "#dept_two", "#dept_three", "#dept_four", "#dept_five", "#dept_six", "#dept_seven"]

# Iterate through the placeholder strings
for i in range (0, len(placeholders)):

    # Find the cell containing the current placeholder string
    cell = worksheet.FindString(placeholders[i], False, False)

    # Replace the value in the found cell with the corresponding department name
    cell.Value = departments[i]
    

# Save the workbook to a different
workbook.SaveToFile("ReplaceText.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Find and replace text in Excel in Python

Add Formulas and Charts to Excel in Python

In addition to basic file operations, Spire.XLS for Python provides a variety of advanced techniques for working with Excel files. For example, you can insert formulas into cells using the CellRange.Formula property, which allows for real-time calculations and data analysis directly within your spreadsheet. Furthermore, it allows you to create visually appealing data presentations by adding charts to your worksheets using the Worksheet.Charts.Add() method.

Here are the steps to add formulas and charts to Excel using Python:

  • Create a Workbook object.
  • Load an Excel file from a given file path.
  • Get a specific worksheet using the Workbook.Worksheets[index] property.
  • Get a specific cell using the Worksheet.Range property.
  • Add a formula to the cell using the CellRange.Formula property.
  • Add a column chart to the worksheet using the Worksheet.Charts.Add() method.
  • Set the chart data range, position, title and other attributes using the properties under the Chart object.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Get all located range
allocatedRange = worksheet.AllocatedRange

#Iterate through the rows
for rowNum in range(0, allocatedRange.RowCount):
    if (rowNum == 0):
        
        # Write text to cell G1
        worksheet.Range[rowNum + 1, 6].Text = "Total"

        # Apply style to the cell
        worksheet.Range[rowNum + 1, 6].Style.Font.IsBold = True
        worksheet.Range[rowNum + 1, 6].Style.HorizontalAlignment = HorizontalAlignType.Right
    else:

        # Add formulas to the cells from G2 to G8
        worksheet.Range[rowNum + 1, 6].Formula = f"=SUM(B{rowNum + 1}:E{rowNum + 1})"

# Add a clustered column chart
chart = worksheet.Charts.Add(ExcelChartType.ColumnClustered)

# Set data range for the chart
chart.DataRange = worksheet.Range["A1:E8"]
chart.SeriesDataFromRange = False

# Set position of the chart
chart.LeftColumn = 1
chart.TopRow = 10
chart.RightColumn = 8
chart.BottomRow = 23

# Set and format chart title
chart.ChartTitle = "Sales by Department per Quarter"
chart.ChartTitleArea.Size = 13
chart.ChartTitleArea.IsBold = True

# Save the workbook to a different
workbook.SaveToFile("AddFormulaAndChart.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Insert formulas and charts in Excel in Python

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

When working with Excel, you might occasionally find your worksheets cluttered with unnecessary rows and columns. These might be leftover data from previous versions, temporary calculations, or placeholders that no longer serve a purpose. Removing these unnecessary or unwanted rows and columns can keep your data organized and your sheets neat. In this article, you will learn how to delete rows and columns from an Excel Worksheet in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with deleting Excel rows and columns in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

npm i spire.xls

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.

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

Delete a Specific Row and Column from Excel

Spire.XLS for JavaScript provides the Worksheet.DeleteRow() and Worksheet.DeleteColumn() methods to delete a specific row and column by index. The following are the main steps.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Delete a specified row by its index (1-based) using the Worksheet.DeleteRow() method.
  • Delete a specified column by its index (1-based) using the Worksheet.DeleteColumn() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to delete a specified row and column 
  const DeleteRowColumn = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Expense.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

      // Load an Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      //Delete the 18th row 
      sheet.DeleteRow({index:18});

      //Delete the 5th
      sheet.DeleteColumn({index:5});
      
      //Save result file
      const outputFileName = 'DeleteRowAndColumn.xlsx';
      workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      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 used by the workbook
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete a Specified Row and Column Using JavaScript in React</h1>
      <button onClick={DeleteRowColumn} disabled={!wasmModule}>
        Delete
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Delete" button to delete the specific row and column:

Run the code to launch the React app at localhost:3000

Below is the input Excel file and the result file:

Remove the last row and last column in an Excel worksheet

Delete Multiple Rows and Columns from Excel

Spire.XLS for JavaScript also allows you to delete multiple adjacent rows and columns from an Excel worksheet at once through the Worksheet.DeleteRow(index, count) and Worksheet.DeleteColumn(index, count) methods. The following are the main steps.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Delete multiple rows from the worksheet using the Worksheet.DeleteRow(index, count) method.
  • Delete multiple columns from the worksheet using the Worksheet.DeleteColumn(index, count) method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to delete multiple rows and columns 
  const DeleteMultiRowsColumns = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'Expense.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

      // Load an Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

      //Delete 5 rows from the 8th row
      sheet.DeleteRow({index:8, count:5});

      //Delete 2 columns from the 4th column
      sheet.DeleteColumn({index:4, count:2});
      
      //Save result file
      const outputFileName = 'DeleteMultiRowsAndColumns.xlsx';
      workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      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 used by the workbook
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Multiple Rows and Columns Using JavaScript in React</h1>
      <button onClick={DeleteMultiRowsColumns} disabled={!wasmModule}>
        Delete
      </button>
    </div>
  );
}

export default App;

Remove multiple rows and columns from an Excel worksheet

Delete Blank Rows and Columns from Excel

To remove the blank rows and column, you need to iterate over each row and column to detect whether they are blank or not. If yes, then remove them from the worksheet. The following are the main steps.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Iterate through the used rows in the worksheet.
  • Find the blank rows using the Worksheet.Rows.get().IsBlank property, and then delete them using the Worksheet.DeleteRow() method.
  • Iterate through the used columns in the worksheet.
  • Find the blank columns using the Worksheet.Columns.get().IsBlank property, and then delete them using the Worksheet.DeleteColumn() method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to delete blank rows and columns 
  const DeleteBlankRowsColumns = async () => {
    if (wasmModule) {
      // Load the input file into the virtual file system (VFS)
      const inputFileName = 'input.xlsx';
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

      // Load an Excel document
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let sheet = workbook.Worksheets.get(0);

        //Delete blank rows from the worksheet.
        for(let i=sheet.Rows.Count-1; i>=0; i--) {
          if(sheet.Rows.get(i).IsBlank) {
            sheet.DeleteRow(i+1);
          }
        }

        //Delete blank columns from the worksheet.
        for(let j=sheet.Columns.Count-1; j>=0; j--) {
          if(sheet.Columns.get(j).IsBlank) {
            sheet.DeleteColumn(j+1);
          }
        }

        //Save result file
        const outputFileName = 'DeleteBlankRowsAndColumns.xlsx';
        workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});
      
      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      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 used by the workbook
      workbook.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Blank Rows and Columns Using JavaScript in React</h1>
      <button onClick={DeleteBlankRowsColumns} disabled={!wasmModule}>
        Delete
      </button>
    </div>
  );
}

export default App;

Rmove blank rows and columns from an Excel worksheet

Get a Free License

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

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:

npm i spire.doc

After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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 wasmModule.Document.Create() 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
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spiredoc from the global window object
        const { Module, spiredoc } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spiredoc);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert RTF to PDF
  const convertRtfToPdf = async () => {
    if (wasmModule) {

      // Load the font files into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('times.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbd.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesbi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('timesi.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Specify the input file path
      const inputFileName = 'input.rtf'; 
   
      // Create a new document
      const doc= wasmModule.Document.Create();

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // 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 = wasmModule.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 wasmModule.Document.Create() 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
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spiredoc from the global window object
        const { Module, spiredoc } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spiredoc);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to convert RTF to HTML
  const convertRtfToHtml = async () => {
    if (wasmModule) {

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

      // Specify the input file path
      const inputFileName = 'input.rtf'; 
   
      // Create a new document
      const doc= wasmModule.Document.Create();

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
      
      // 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 = wasmModule.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.

page 21