Convert Word to JPG and PNG with JavaScript in React

Converting Word documents to JPG or PNG formats is a practical solution for sharing visual content. This transformation preserves the layout and design, making it ideal for presentations, websites, or social media. Whether for professional or personal use, converting Word files to images simplifies accessibility and enhances visual appeal, allowing for easy integration into various digital platforms.

In this article, you will learn how to convert Word to JPG and PNG in React using Spire.Doc for JavaScript.

Install Spire.Doc for JavaScript

To get started with converting Word documents to image files 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 Word to JPG with JavaScript

Spire.Doc for JavaScript includes the Document.SaveImageToStreams() method, which enables users to convert a specific page of a Word document into an image stream. This stream can then be saved in various formats such as JPG, PNG, or BMP using the Save() method of the image stream object.

The following are the detailed steps to convert a Word document to JPG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the new wasmModule.Document() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a JPG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the JPG file.
  • 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 Word to JPG
  const convertWord = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, type: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.jpg`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/jpeg' });

        // Create download link
        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);
      }
      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to JPG in React</h1>
      <button onClick={convertWord} 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 one of the generated JPG files:

Convert Word to JPG

Convert Word to PNG with JavaScript

The example above illustrates how to convert Word documents to JPG images. To convert to PNG, you only need to change the image format to PNG in the code.

The following are the detailed steps to convert a Word document to PNG files with JavaScript in React:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the new wasmModule.Document() method
  • Load the Word document using the Document.LoadFromFile() method.
  • Loop through the pages in the document:
    • Convert a specific page into image stream using the Document.SaveImageToStreams() method.
    • Save the image stream to a PNG file using the Save() method of the image stream object.
    • Read the generated image file from the VFS.
    • Create a Blob object from the image data.
    • Trigger the download of the PNG file.
  • 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 Word to JPG
  const convertWord = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Get the total number of pages in the document
      const totalPages = doc.GetPageCount();

      // Loop through each page and convert it to an image
      for (let pageIndex = 0; pageIndex < totalPages; pageIndex++) {

        // Convert the specific page to an image stream
        let img = doc.SaveImageToStreams({ pageIndex, type: wasmModule.ImageType.Bitmap });

        // Specify output file name based on page index
        const outputFileName = `IMG-${pageIndex}.png`;

        // Save the image stream to a JPG file
        img.Save(outputFileName);

        const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
        const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

        // Create download link
        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);
      }
      // dispose 
      doc.Dispose();

    }

  };

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

export default App;

Convert Word to PNG

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.

Converting Excel worksheets into image formats like PNG or JPEG can be useful for sharing spreadsheet data in presentations, reports, or other documents. Unlike Excel files, image formats ensure that the formatting and structure remain consistent, regardless of the viewer’s software or platform. In this article, we will demonstrate how to convert Excel to images in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

Copy
npm i spire.office

The downloaded product package has been integrated Spire.Doc for JavaScript,Spire.XLS for JavaScript,Spire.PDF for JavaScript,Spire.Presentation for JavaScript. To use the functionality of Spire.XLS for JavaScript, you need to copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and _framework) to the project's "public" folder. At the same time, in order to ensure text rendering, the related font files can be added with custom paths. In the following example, the font addition path is: public\static\font.

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

Convert an Excel Worksheet to an Image with JavaScript in React

Spire.XLS for JavaScript allows you to convert a worksheet into an image using the Worksheet.ToImage() function. Once the conversion is complete, you can save the image in formats such as PNG, JPG, or BMP with the Image.Save() function. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Convert the worksheet to an image using the Worksheet.ToImage() function.
  • Save the image to a PNG file using the Image.Save() function (you can also save the image in other image formats such as JPG and BMP).

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert an Excel Worksheet to an Image
  const ExcelToImage = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Convert the sheet to an image
      let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);

      // Specify the output image file path
      const outputFileName = 'SheetToImage.png';
      //Save the image
      image.Save(outputFileName);

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to Image Using JavaScript in React</h1>
      <button onClick={ExcelToImage} disabled={!wasmModule}>
        Convert
      </button>
    
); } export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the specified Excel worksheet to image:

React app runs at localhost:3000

The below screenshot shows the input Excel worksheet and the converted image:

Convert an Excel Worksheet to an Image with JavaScript in React

Convert an Excel Worksheet to an Image without White Margins with JavaScript in React

When converting an Excel worksheet to an image, the default output may include unnecessary white margins that can affect the appearance and usability of the image. If you want to remove these white margins, you can set the left, right, top, and bottom margins of the worksheet to zero. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Remove all margins from the worksheet by setting its left, right, top, and bottom margin values to zero using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties.
  • Convert the worksheet to an image using the Worksheet.ToImage() function.
  • Save the image to a PNG file using the Image.Save() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert an Excel Worksheet to an Image
  const ExcelToImage = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Set all margins of the worksheet to zero
      sheet.PageSetup.LeftMargin = 0;
      sheet.PageSetup.BottomMargin = 0;
      sheet.PageSetup.TopMargin = 0;
      sheet.PageSetup.RightMargin = 0;

      // Convert the sheet to image
      let image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn);

      // Specify the output image file path
      const outputFileName = 'SheetToImageWithoutMargins.png';
      //Save the image
      image.Save(outputFileName);

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to Image Using JavaScript in React</h1>
      <button onClick={ExcelToImage} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert an Excel Worksheet to an Image without White Margins with JavaScript in React

Convert a Specific Cell Range to an Image with JavaScript in React

Converting a specific cell range to an image lets you highlight essential data, making it easy to share or embed without including unnecessary information. Spire.XLS for JavaScript enables you to convert a specific cell range from a worksheet into an image by providing the starting and ending row and column indices as parameters to the Worksheet.ToImage() function. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Convert a specific cell range of the worksheet to an image using the Worksheet.ToImage() function and pass the index of the start row, start column, end row, and end column of the cell range to the method as parameters.
  • Save the image to a PNG file using the Image.Save() function

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert an Excel Worksheet to an Image
  const ExcelToImage = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Convert a specific cell range of the worksheet to image
      let image = sheet.ToImage(5, 2, 17, 5);

      // Specify the output image file path
      const outputFileName = 'CellRangeToImage.png';
      //Save the image
      image.Save(outputFileName);

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'image/png' });

      // Create a URL for the Blob and initiate 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>Convert a Cell Range to Image Using JavaScript in React</h1>
      <button onClick={ExcelToImage} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Specific Cell Range to an Image with JavaScript in React

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.

Spire.XLS for JavaScript is an independent Word API that allows developers to integrate Microsoft Word document creation capabilities into their JavaScript applications, without installing Microsoft Word on either development or target systems.

Spire.XLS for JavaScript is fully compatible with popular frameworks such as Vue, React, Angular, and JavaScript, enabling developers to create and distribute their own JavaScript applications seamlessly across the web.

This versatile JavaScript Excel API operates independently, with no reliance on Microsoft Office Excel. Spire.XLS for JavaScript supports both the legacy Excel 97-2003 format (.xls) and the most recent Excel versions, including Excel 2007, 2010, 2013, 2016, and 2019 (.xlsx, .xlsb, .xlsm), as well as Open Office (.ods) format.

Microsoft Excel is a powerful tool for managing and analyzing data, but its file format can be difficult to share, especially when recipients don’t have Excel. Converting an Excel file to PDF solves this problem by preserving the document’s layout, fonts, and formatting, ensuring it looks the same on any device. PDFs are universally accessible, making them ideal for sharing reports, invoices, or presentations. They also prevent unwanted editing, ensuring the content remains intact and easily viewable by anyone. In this article, we will demonstrate how to convert Excel to PDF in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

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

Copy
npm i spire.office

The downloaded product package has been integrated Spire.Doc for JavaScript,Spire.XLS for JavaScript,Spire.PDF for JavaScript,Spire.Presentation for JavaScript. To use the functionality of Spire.XLS for JavaScript, you need to copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and _framework) to the project's "public" folder. At the same time, in order to ensure text rendering, the related font files can be added with custom paths. In the following example, the font addition path is: public\static\font.

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

Convert an Entire Excel Workbook to PDF

Converting an entire Excel workbook to PDF allows users to share all sheets in a single, universally accessible file. Using the Workbook.SaveToFile() function of Spire.XLS for JavaScript, you can easily save the entire workbook in PDF format. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Save the Excel file to PDF using the Workbook.SaveToFile() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify output PDF file path
      const outputFileName = 'out.pdf';

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

      // Load existing Excel document
      workbook.LoadFromFile({ fileName: inputFileName });
      workbook.ConverterSetting.SheetFitToPage = true;

      // Save the workbook as PDF
      workbook.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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> Convert Excel file to PDF using JavaScript in React </h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to download the PDF version of the Excel file:

React app runs at localhost:3000

Below is the converted PDF document:

Convert an Entire Excel Workbook to PDF

Convert a Specific Worksheet to PDF

To convert a single worksheet to PDF, use the Worksheet.SaveToPdf() function in Spire.XLS for JavaScript. This feature lets you efficiently extract and convert only the necessary worksheet, making your reporting process more streamlined. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF  = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Specify output PDF file path
      const outputFileName = 'out.pdf';

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Specific Worksheet to PDF

Fit Sheet on One Page while Converting a Worksheet to PDF

Fitting a worksheet onto a single page in the output PDF enhances readability, especially for large datasets. Spire.XLS for JavaScript offers the Workbook.ConverterSetting.SheetFitToPage property, which determines whether the worksheet content should be scaled to fit on a single page when saved as a PDF. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Fit the worksheet on one page by setting the Workbook.ConverterSetting.SheetFitToPage property to true.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF  = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

      // Fit sheet on one page
      workbook.ConverterSetting.SheetFitToPage = true;

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

      // Specify the output PDF file path
      const outputFileName = 'FitSheetOnOnePage.pdf';

      //Save the worksheet to PDF
      sheet.SaveToPdf({fileName: outputFileName});

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Customize Page Margins while Converting a Worksheet to PDF

Customizing page margins when converting an Excel worksheet to PDF ensures that your content is well-aligned and visually appealing. Using the Worksheet.PageSetup.TopMargin, Worksheet.PageSetup.BottomMargin, Worksheet.PageSetup.LeftMargin, and Worksheet.PageSetup.RightMargin properties, you can adjust or remove page margins as needed. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Adjust the page margins of the worksheet using the Worksheet.PageSetup.PageMargins property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Adjust page margins of the worksheet
      sheet.PageSetup.TopMargin = 0.5;
      sheet.PageSetup.BottomMargin = 0.5;
      sheet.PageSetup.LeftMargin = 0.3;
      sheet.PageSetup.RightMargin = 0.3;

      // Specify the output PDF file path
      const outputFileName = 'ToPdfWithSpecificPageMargins.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({ fileName: outputFileName });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Specify Page Size while Converting a Worksheet to PDF

Choosing the correct page size when converting an Excel worksheet to PDF is essential for meeting specific printing or submission standards. Spire.XLS for JavaScript offers the Worksheet.PageSetup.PaperSize property, which allows you to select from various predefined page sizes or set a custom size. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Set the page size of the worksheet using the Worksheet.PageSetup.PaperSize property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Set the page size of the worksheet
      sheet.PageSetup.PaperSize = wasmModule.PaperSizeType.PaperA3;

      // Specify the output PDF file path
      const outputFileName = 'ToPdfWithSpecificPageSize.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({ fileName: outputFileName });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Cell Range to PDF

Converting a specific cell range to PDF allows users to export only a selected portion of the worksheet, ideal for focused reporting or sharing key data points. Using the Worksheet.PageSetup.PrintArea property, you can specify a cell range for conversion. The key steps are as follows.

  • Load the font file to ensure correct text rendering.
  • Create a Workbook object using the new wasmModule.Workbook() function.
  • Load the Excel file using the Workbook.LoadFromFile() function.
  • Get a specific worksheet using the Workbook.Worksheets.get(index) function.
  • Specify the cell range of the worksheet for conversion using the Worksheet.PageSetup.PrintArea property.
  • Save the worksheet to PDF using the Worksheet.SaveToPdf() function.

Code example:

  • JavaScript
Copy
import React, { useState, useEffect } from 'react';
function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Function to convert Excel file to PDF
  const ExcelToPDF = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into Virtual File System (VFS)
      await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

      // Load input file into Virtual File System (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

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

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

      // Set the page size of the worksheet
      sheet.PageSetup.PrintArea = "B5:E17";

      // Specify the output PDF file path
      const outputFileName = 'CellRangeToPDF.pdf';
      //Save the worksheet to PDF
      sheet.SaveToPdf({ fileName: outputFileName });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create a URL for the Blob and initiate 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>Convert an Excel Worksheet to PDF Using JavaScript in React</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Convert
      </button>
    </div>
  );
}

export default App;

Convert a Cell Range to PDF

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.

Converting Word documents to PDF is crucial for maintaining formatting and ensuring consistent viewing across various devices. This conversion process protects the content and layout, making PDFs a preferred choice for sharing official documents such as contracts and reports. PDFs not only preserve the original design but also enhance security, as they are less susceptible to unauthorized edits.

This article demonstrates how to convert Word documents to PDF in React using Spire.Doc for JavaScript. It covers the installation process and provides practical examples to help you configure different conversion options efficiently.

Install Spire.Doc for JavaScript

To get started with converting Word documents to PDF 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

General Steps to Convert Word to PDF in React

Converting Word documents to PDF in React using Spire.Doc for JavaScript involves several key steps. Here's a step-by-step guide to help you get started:

  1. Load Fonts: Load necessary font files into the virtual file system (VFS) for accurate rendering.
  2. Prepare Document: Fetch the input Word file, create a new document, and load the file into it.
  3. Set PDF Conversion Parameters: Configure any necessary conversion options, such as embedding fonts or preserving bookmarks.
  4. Convert to PDF: Convert the document to PDF with the specified options.
  5. Download PDF: Read the generated PDF from the VFS, create a Blob object, and trigger the download for the user.

Convert Word to PDF with Installed Fonts Embedded

When converting documents, you may want to ensure that all fonts used in the Word document are embedded into the PDF. This is especially important for maintaining the document's layout.

Spire.Doc for JavaScript offer the ToPdfParameterList class to customize the conversion options. The key parameter set here is IsEmbeddedAllFonts, which guarantees that all fonts are included in the final PDF.

The following code snippet demonstrates how to embed installed fonts when converting Word to PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Create a parameter list for the PDF conversion
      let parameters = new wasmModule.ToPdfParameterList();

      // Set the parameter to embed all fonts in the PDF
      parameters.IsEmbeddedAllFonts = true;

      // Specify the input and output file paths
      const outputFileName = 'ToPDF.pdf';

      // Save the document as a PDF file
      doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PDF Using JavaScript in React</h1>
      <button onClick={convertWordToPdf} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

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

React app that allows users to convert word to pdf

Below is a screenshot of the generated PDF document:

The PDF generated from Word with all used fonts embedded

Convert Word to PDF with Non-Installed Fonts Embedded

For fonts that are not installed on your machine but applied in the Word document, you can also embed these fonts directly into the PDF. This ensures that the document looks consistent across different devices.

To embed non-installed fonts, start by creating a ToPdfParameterList object to customize the conversion process. Next, define a list of custom fonts for the PDF output. Finally, assign the custom font paths to the parameters using the ToPdfParameterList.PrivateFontPaths property.

The following code snippet demonstrates how to embed non-installed fonts when converting Word to PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = async () => {
    const wasmModule = window.wasmModule.spiredoc;
    if (wasmModule) {
      // Load the font files into the virtual file system (VFS)
      await window.spire.FetchFileToVFS('FreebrushScriptPLng.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Create a parameter list for the PDF conversion
      let parameters = new wasmModule.ToPdfParameterList();

      // Define a list of custom fonts to be used in the PDF
      let fonts = new wasmModule.PrivateFontPath('Freebrush Script', 'FreebrushScriptPLng.ttf');

      // Assign the custom font paths to the parameters for the PDF conversion
      parameters.PrivateFontPaths = fonts;

      // Save the document as a PDF file
      const outputFileName = 'ToPDF.pdf';
      doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

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

The PDF file generated from Word with non-installed fonts embedded

Convert Word to Password-Protected PDF

To enhance security, you can convert a Word document to a password-protected PDF. This feature is essential when sharing sensitive information.

Spire.Doc for JavaScript provides the ToPdfParameterList.PdfSecurity.Encrypt() method, enabling users to protect the generated PDF with an open password, a permission password, and specific document permissions.

The following code illustrates how to convert Word to password-protected PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Create a parameter list for the PDF conversion
      let parameters = new wasmModule.ToPdfParameterList();

      // Set the parameter to encrypt the generated PDF file
      parameters.PdfSecurity.Encrypt('open-psd', 'permission-psd', wasmModule.PdfPermissionsFlags.Default, wasmModule.PdfEncryptionKeySize.Key128Bit);

      // Save the document as a PDF file
      const outputFileName = 'Encrypted.pdf';
      doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PDF Using JavaScript in React</h1>
      <button onClick={convertWordToPdf} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Convert Word to password-protected PDF

Convert Word to PDF with Hyperlinks Disabled

Disabling hyperlinks when converting a Word document to PDF enhances readability and maintains a clean, distraction-free format. This adjustment can be particularly useful for print materials, presentations, and documents requiring a focus on content without external links.

By setting the ToPdfParameterList.DisableLink property to true, you can ensure that any clickable links in the original document are rendered as plain text in the PDF output.

The following code snippet demonstrates how to disable hyperlinks when converting Word to PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Create a parameter list for the PDF conversion
      let parameters = new wasmModule.ToPdfParameterList();

      // Set the parameter to disable hyperlinks
      parameters.DisableLink = true;

      // Save the document as a PDF file
      const outputFileName = 'DisableHyperlinks.pdf';
      doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PDF Using JavaScript in React</h1>
      <button onClick={convertWordToPdf} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Convert Word to PDF with Bookmarks Preserved

Preserving bookmarks when converting a Word document to PDF enhances navigation in lengthy documents, allowing readers to quickly access specific sections. This feature improves usability and the overall experience of the PDF.

To create bookmarks in the output PDF document from the existing Word bookmarks, set the ToPdfParameterList.CreateWordBookmarks property to true.

The following is an example of preserving bookmarks when converting Word to PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Create a parameter list for the PDF conversion
      let parameters = new wasmModule.ToPdfParameterList();

      // Set the parameter to create bookmarks in the PDF from existing bookmarks in Word
      parameters.CreateWordBookmarks = true;

      // Save the document as a PDF file
      const outputFileName = 'CreateBookmarks.pdf';
      doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PDF Using JavaScript in React</h1>
      <button onClick={convertWordToPdf} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Preserve bookmarks when converting Word to PDF

Convert Word to PDF with Custom Image Quality

If your Word document contains images, you may want to control the quality of these images in the PDF. This can help balance file size and quality.

Spire.Doc for JavaScript includes the Document.JPEGQuality property, which allows developers to set image compression quality on a scale from 1 to 100.

The following is an example of customizing image quality when converting Word to PDF using JavaScript.

  • 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 Word to PDF
  const convertWordToPdf = 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/`);

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

      // Create a new document
      const doc = new wasmModule.Document();

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

      // Set the output image quality to be 40% of the original image
      doc.JPEGQuality = 40;

      // Save the document as a PDF file
      const outputFileName = 'CustomImageQuality.pdf';
      doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF });

      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });

      // Create download link
      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);

      // dispose 
      doc.Dispose();

    }

  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert Word to PDF Using JavaScript in React</h1>
      <button onClick={convertWordToPdf} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

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.

Spire.Doc for JavaScript is an independent Word API that allows developers to integrate Microsoft Word document creation capabilities into their JavaScript applications, without installing Microsoft Word on either development or target systems.

It is a trustworthy MS Word API for JavaScript that can apply multiple Word document processing tasks. Spire.Doc for JavaScript supports Word 97-2003 /2007/2010/2013/2016/2019, and it has the capability of converting them to other common formats, like XML, RTF, TXT, EMF, HTML, ODT, Markdown, and vice versa. Moreover, it supports converting Word Doc/Docx to PDF, images (PNG, JPEG), PostScript, OFD, XPS, EPUB, PCL (Printer Command Language), and RTF to PDF/HTML, HTML to PDF/Image, Markdown to PDF in high quality.

Integrating document processing capabilities is crucial for enhancing user experience in many web applications, allowing for efficient report generation and data handling. React, with its component-based architecture, is an excellent choice for frontend development. By integrating Spire.Doc for JavaScript, you can effortlessly create and manage Word documents within your React application.

This guide will walk you through the steps to integrate Spire.Doc for JavaScript into your React projects, covering both setup and a usage example.

Benefits of Using Spire.Doc for JavaScript in React

React, a popular JavaScript library for building user interfaces, has become a cornerstone in modern web development. On the other hand, Spire.Doc for JavaScript is a powerful library designed to simplify document processing in web applications.

By integrating Spire.Doc for JavaScript into your React project, you can add advanced Word document processing capabilities to your application. Here are some of the key advantages:

  • Seamless Document Creation: Spire.Doc for JavaScript enables document creation and editing directly in React, streamlining management without external tools.
  • Cross-Platform Compatibility: Spire.Doc for JavaScript allows document creation compatible with multiple platforms, enabling users to access and edit documents from anywhere.
  • Rich Features: Spire.Doc for JavaScript offers extensive capabilities like text formatting, table creation, and image insertion, ideal for applications needing document manipulation.
  • Seamless Integration: Compatible with various JavaScript frameworks, including React, Spire.Doc for JavaScript integrates easily into existing projects without disrupting your workflow.

Set Up Your Environment

Step 1. Install React and npm

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are working correctly by running the following commands in your terminal:

Check the versions of node.js and npm

Step 2. Create a New React Project

Create a new React project named my-app using Create React App from terminal:

npx create-react-app my-app

Create a react project

If your React project is compiled successfully, the app will be served at http://localhost:3000, allowing you to view and test your application in a browser.

React app opens at localhost 3000

To visually browse and manage the files in your project, you can open the project using VS Code.

Open React project in VS Code

Integrate Spire.Doc for JavaScript in Your Project

Download Spire.Doc for JavaScript from our website and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Doc.Base.js and Spire.Doc.Base.wasm files.

Download Spire.Doc for JavaScript library

You can also install Spire.Doc for JavaScript using npm. In the terminal within VS Code, run the following command:

npm i spire.doc

Install Spire.Doc for JavaScript from npm

This command will download and install the Spire.Doc package, including all its dependencies. Once the installation is complete, the Spire.Doc.Base.js and Spire.Doc.Base.wasm files will be saved in the node_modules/spire.doc path of your project.

The library files installed via npm

Copy these two files into the "public" folder in your React project.

Copy library to React project

Add font files you plan to use to the "public" folder in your project.

Add font files to React project

Create and Save Word Files Using JavaScript

Modify the code in the "App.js" file to generate a Word file using the WebAssembly (WASM) module. Specifically, utilize the Spire.Doc for JavaScript library for Word file manipulation.

Modify app.js file

Here is the entire code:

  • 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 generate word file
  const createWord = async () => {
    if (wasmModule) {

      // Load the ARIALUNI.TTF font file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      
      // Specify output file name
      const outputFileName = 'HelloWorld.docx';

      // Create a new document
      const doc = wasmModule.Document.Create();

      // Add a section
      let section = doc.AddSection();

      // Add a paragraph
      let paragraph = section.AddParagraph();

      // Append text to the paragraph
      paragraph.AppendText('Hello, World!');

      // Save the document to a Word file
      doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013});
      
      // 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.wordprocessingml.document' });
      
      // 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
      doc.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Create a Word File Using JavaScript in React</h1>
      <button onClick={createWord} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Save the changes by clicking "File" - "Save".

Save changes

Start the development server by entering the following command in the terminal within VS Code:

npm start

Start your react project by running npm start

Once the React app is successfully compiled, it will open in your default web browser, typically at http://localhost:3000.

 React app opens at local host 3000

Click "Generate" and a "Save As" window will prompt you to save the output file in the designated folder.

Save the generated Word at the specified folder

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.

In today's data-driven landscape, efficiently handling Excel files is crucial for web applications. React, a widely-used JavaScript library for user interfaces, can significantly enhance its capabilities by integrating Spire.XLS for JavaScript. This integration allows developers to perform complex operations like reading, writing, and formatting Excel files directly within their React projects.

This article will walk you through the integration of Spire.XLS for JavaScript into your React projects, covering everything from the initial setup to a straightforward usage example.

Benefits of Using Spire.XLS for JavaScript in React Projects

React, a popular JavaScript library for building user interfaces, has revolutionized web development by enabling developers to create interactive and dynamic user experiences. On the other hand, Spire.XLS for JavaScript is a powerful library that allows developers to manipulate Excel files directly in the browser.

By integrating Spire.XLS for JavaScript into your React project, you can add advanced Excel capabilities to your application. Here are some of the key advantages:

  • Enhanced Functionality: Spire.XLS for JavaScript enables creating, modifying, and formatting Excel files directly in the browser, enhancing your React app's capabilities and user experience.
  • Improved Data Management: Easily import, export, and manipulate Excel files with Spire.XLS, streamlining data management and reducing errors.
  • Cross-Browser Compatibility: Designed to work seamlessly across major web browsers, Spire.XLS ensures consistent handling of Excel files in your React application.
  • Seamless Integration: Compatible with various JavaScript frameworks, including React, Spire.XLS integrates easily into existing projects without disrupting your workflow.

Set Up Your Environment

Step 1. Install Node.js and npm

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are working correctly by running the following commands in your terminal:

node -v
npm -v

Check versions of node.js and npm

Step 2. Create a New React Project

Create a new React project named my-app using Create React App from terminal:

npx create-react-app my-app

Create a react project

Once the project is created, you can navigate to the project directory and start the development server using the following commands:

cd my-app
npm start

Start development server

If your React project is compiled successfully, the app will be served at http://localhost:3000, allowing you to view and test your application in a browser.

Open react app at localhost 3000

To visually browse and manage the files in your project, you can open the project using VS Code.

Open React project in VS Code

Integrate Spire.XLS for JavaScript in Your Project

Download Spire.XLS for JavaScript from our website and unzip it to a location on your disk. The downloaded product package has been integrated Spire.Doc for JavaScript,Spire.XLS for JavaScript,Spire.PDF for JavaScript,Spire.Presentation for JavaScript. To use the functionality of Spire.XLS for JavaScript, you need to copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and _framework) to the project's “public” folder.

Get Spire.XLS for JavaScript library

You can also install Spire.XLS for JavaScript using npm. In the terminal within VS Code, run the following command:

npm i spire.office

After downloading this command, find the corresponding file in the node_comodules/spire.office path of the project and copy it to “public” folder.

At the same time, in order to ensure text rendering, the related font files can be added with custom paths. In the following example, the font addition path is: public\font.

Copy library to React project

Create Excel files using JavaScript

Modify the code in the "App.js" file to generate an Excel file using the WebAssembly (WASM) module. Specifically, utilize the Spire.XLS for JavaScript library for Excel file manipulation.

Rewrite code for app.js

  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {
  const [wasmModule, setWasmModule] = useState(null);
  // Load Spire.XLS
  useEffect(() => {
    (async () => {
      try {
        const publicUrl = process.env.PUBLIC_URL || '';
        const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.xls.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.xls.js WASM module:', error);
      }
    })();
  }, []);

  // Create HelloWorld.xlsx
  const ExcelToPDF = async () => {
    const wasmModule = window.wasmModule.spirexls;

    if (wasmModule) {
      // Load font into virtual file system (VFS)
      await window.spire.FetchFileToVFS('arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

      // Create a new workbook
      const workbook = new wasmModule.Workbook();

      // Clear default worksheets
      workbook.Worksheets.Clear();

      // Add a new worksheet named "MySheet"
      const sheet = workbook.Worksheets.Add("MySheet");

      // Set the text of cell "A1"
      sheet.Range.get("A1").Text = "Hello World";

      // Set column width to auto-fit
      sheet.Range.get("A1").AutoFitColumns();

      // Define output file name
      const outputFileName = 'HelloWorld.xlsx';

      // Save the workbook to the specified path
      workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 });

      // Read the saved file and convert to Blob object
      const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      // Create a URL for the Blob and start 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>Create HelloWorld.xlsx</h1>
      <button onClick={ExcelToPDF} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Using "npm start" to run the program, and click "Generate" to download the generated Excel file.

Save the changes made to app.js

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.

Document processing is an essential feature in many modern web applications, enabling tasks such as report generation and data management. Node.js, known for its non-blocking I/O model and extensive ecosystem, provides a powerful platform for backend development. By integrating Spire.Doc for JavaScript, you can streamline the creation and manipulation of Word documents effortlessly.

This guide will take you through the steps to integrate Spire.Doc for JavaScript into your Node.js projects, from initial setup to a basic usage example.

Benefits of Using Spire.Doc for JavaScript in Node.js Projects

Node.js is a powerful runtime environment that allows developers to build scalable network applications using JavaScript. Spire.Doc for JavaScript, on the other hand, is a versatile library designed to manipulate Word documents within JavaScript environments. It provides a wide range of features, including document creation, editing, conversion, and more, making it a valuable tool for developers working with document-based applications.

Integrating Spire.Doc for JavaScript into your Node.js project offers numerous benefits, including:

  • Efficient Document Management: Easily create, edit, and manage Word documents without the need for Microsoft Word.
  • Scalability: Leverage Node.js's non-blocking I/O model to handle large volumes of document processing tasks efficiently.
  • Cross-Platform Compatibility: Use Spire.Doc for JavaScript across various platforms, including Windows, macOS, and Linux.
  • Ease of Integration: Seamlessly integrate Spire.Doc for JavaScript with other Node.js libraries and tools.

These benefits make Spire.Doc for JavaScript an ideal choice for developers looking to enhance their Node.js projects with robust document processing capabilities.

Set Up Your Environment

Step 1

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are installed correctly, along with the version numbers, by entering the following commands in CMD:

node -v 
npm -v

Install Node.js

Step 2

Create a Node.js project in your IntelliJ IDEA.

Create a Node.js project

Install Jest in your project to write and run tests for your code, by running the following command in Terminal:

npm install --save-dev jest

Install jest

Create a JavaScript file named "jest.config.js" in your project, and include the following configuration in it.

module.exports = {
    testTimeout: 20000,
    testEnvironment: 'node',
    transform: {},
    testMatch: ['<rootDir>/*.js'],
    moduleFileExtensions: [ 'json', 'node', 'tsx', 'ts', 'js', 'jsx','mjs'],
};

Configure jest

Add a "fonts" folder and a "lib" folder to your project.

Add folders in Node.js project

Integrate Spire.Doc for JavaScript in Your Project

Download Spire.Doc for JavaScript and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Doc.Base.js and Spire.Doc.Base.wasm files.

Download Spire.Doc for JavaScript library

Copy these two files into the "lib" folder in your Node.js project.

Copy library to Node.js project

Place the font files you plan to use into the "fonts" folder in your project.

Add font files to node.js project

Create and Save Word Files Using JavaScript

Add a JavaScript file in your project to generate a simple Word document from JavaScript code.

JavaScript code for creating a Word file

Here is the entire JavaScript code:

  • JavaScript
// Import the library
const { Module, spiredoc } = require("./lib/Spire.Doc.Base.js");

// Define a test case
test('testCase', async () => {
    await new Promise((resolve) => {
        Module.onRuntimeInitialized = () => {
            createWord();
            resolve();
        };
    });
});

// Create a custom function
function createWord(){

    // Load fonts
    spiredoc.copyLocalPathToVFS("fonts/","/Library/Fonts/");

    // Specify output file name and path
    const outputFileName = "HelloWorld.docx";
    const outputPath=  "result/" + outputFileName;

    // Create a new document
    const document = Module.spiredoc.Document.Create();

    // Add a section
    let section = document.AddSection();

    // Add a paragraph
    let paragraph = section.AddParagraph();

    // Append text to the paragraph
    paragraph.AppendText("Hello, World!");

    // Save the document to a Word file
    document.SaveToFile({fileName: outputFileName, fileFormat: spiredoc.FileFormat.Docx2013,
    });
    spiredoc.copyFileFromFSToLocalStorage(outputFileName, outputPath);

    // Dispose resources
    document.Dispose();
}

Once you run the code, you will find the generated Word file in the designated file path.

A Word file generated by JavaScript code

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.

Excel manipulation is a crucial aspect of many modern web applications, from data analysis to report generation. Node.js, with its non-blocking I/O model and rich ecosystem, is an excellent choice for backend development. When combined with Spire.XLS for JavaScript, you can unlock a world of possibilities for handling Excel files efficiently.

This guide will walk you through the process of integrating Spire.XLS for JavaScript into your Node.js projects, covering everything from initial setup to generating a simple Excel document.

Benefits of Using Spire.XLS for JavaScript in Node.js Projects

Node.js is a great option for developing scalable network applications. When paired with Spire.XLS for JavaScript, you get a robust solution for handling Excel files. Here are some key features and benefits of using Spire.XLS for JavaScript in Node.js projects:

  • Comprehensive Excel Support: Spire.XLS for JavaScript supports a wide range of Excel features, including formulas, charts, pivot tables, and more.
  • High Performance: The library is optimized for speed, ensuring that your application remains responsive even when handling large datasets.
  • Cross-Platform Compatibility: With Node.js, you can run your application on any platform that supports JavaScript, including Windows, macOS, and Linux.
  • Secure and Reliable: The library is designed to be secure, with features like data validation and encryption to protect your data.

By leveraging the strengths of both Node.js and Spire.XLS for JavaScript, you can build powerful applications that handle Excel files with ease.

Set Up Your Environment

Step 1

Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.

After the installation is complete, you can verify that Node.js and npm are installed correctly, along with the version numbers, by entering the following commands in CMD:

node -v 
npm -v 

Install Node.js

Step 2

Initialize a Node.js project:

npm init -y

Installation dependencies:

npm install adm-zip@^0.5.16 

Configure packaging.json:

{
	"name": "nodejstest",
    "version": "1.0.0",
    "description": "Simple test project to generate HelloWorld.xlsx using spire.xls.js",
    "main": "index.js",
    "type": "module",
    "scripts": {
      "start": "node --experimental-modules --experimental-wasm-modules --experimental-vm-modules index.js"
    },
    "dependencies": {
      "adm-zip": "^0.5.16"
    }
  }

Customize folder in the root directory to put some font files, you can customize and add fonts based on the font used in your documents.

Add folders in Node.js project

Integrate Spire.XLS for JavaScript in Your Project

Download Spire.XLS for JavaScript and unzip it to a location on your disk. 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.XLS for JavaScript, customize the folder in the root directory, this tutorial defined the 'wasm' folder, and copy the corresponding files (spire.xls.js, Spire.Xls.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the “wasm” folder.

Obtain Spire.XLS for JavaScript library

Add the 'index.js' file to the root directory of the project and set the following content to create a simple Excel file

  • JavaScript
//NodeJSTest----create "HelloWorld.xlsx"
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import AdmZip from 'adm-zip';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function extractWasmFiles() {
    const wasmDir = path.join(__dirname, 'wasm');
    const frameworkDir = path.join(wasmDir, '_framework');
    await fs.mkdir(frameworkDir, { recursive: true });

    for (const zipName of ['Spire.Common.Wasm.zip', 'Spire.Xls.Wasm.zip']) {
        const zipPath = path.join(wasmDir, zipName);
        try {
            await fs.access(zipPath);
            new AdmZip(zipPath).extractAllTo(wasmDir, true);
        } catch { }
    }
}

async function main() {
    try {
        await extractWasmFiles();
        const { spirexls } = await import('./wasm/spire.xls.js');
        const spire = globalThis.spire;
        if (!spire) throw new Error('WASM module not loaded correctly');

        const outputDir = path.join(__dirname, 'output');
        await fs.mkdir(outputDir, { recursive: true });

        const fontsPath = path.join(__dirname, 'fonts');
        try {
            await fs.access(fontsPath);
            spire.copyLocalPathToVFS(fontsPath, '/Library/Fonts/');
        } catch { }

        // Create a new workbook
        const workbook = new spirexls.Workbook();

        // Clear default worksheets
        workbook.Worksheets.Clear();

        // Add a new worksheet named "MySheet"
        const sheet = workbook.Worksheets.Add("MySheet");

        // Set text for the "A1" range
        sheet.Range.get("A1").Text = "Hello World";

        // Set the column width to auto fit
        sheet.Range.get("A1").AutoFitColumns();

        // Define the output file name
        const outputFileName = 'HelloWorld.xlsx';

        // Save the workbook to the specified path
        workbook.SaveToFile({ fileName: outputFileName, version: spirexls.ExcelVersion.Version2010 });

        const outputFile = path.join(outputDir, outputFileName);
        spire.copyFileFromFSToLocalStorage(outputFileName, outputFile);
        workbook.Dispose();

        console.log(`Document saved to ${outputFile}`);
    } catch (error) {
        console.error(error);
        process.exit(1);
    }
}

main();

Using “npm start” run the program, you will find the generated Word file in the designated file path.

Excel file generated by JavaScript code.

Excel file generated by JavaScript code.

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.

Page 4 of 4
page 4