DEV Community

jelizaveta
jelizaveta

Posted on

How to Convert Excel to PDF Using JavaScript (With Parameter Settings)

Have you ever needed to turn an Excel spreadsheet into a PDF directly in the browser? It’s a very common need, whether you’re generating reports, storing data, or showing previews. PDF wins because it works everywhere and looks consistent. Thanks to Spire.XLS for JavaScript, we can do this entirely on the front end – no server, no Office installation – with just a few lines of code. This tutorial starts from zero, sets up a React example, and covers many customization options.

1. Why Choose Spire.XLS for JavaScript?

Spire.XLS for JavaScript is a pure front‑end Excel manipulation library based on WebAssembly. It allows you to create, read, modify, and convert Excel documents in the browser without installing Office or any local software. Its core advantages include:

  • Cross‑platform : Supports all modern browsers (Chrome, Firefox, Edge, etc.) as well as Node.js.
  • High performance : Built on WASM, it handles large files smoothly.
  • Rich features : Not only supports conversion, but also enables manipulation of cells, styles, charts, pivot tables, and more.
  • No network required : All processing is done locally, without relying on cloud services, ensuring data privacy.

In this article, we will focus on how to use it to convert Excel → PDF and extend it with various custom settings.

2. Installation and Initialization

First, install the spire.office package in your project:

npm i spire.office
Enter fullscreen mode Exit fullscreen mode

After installation, you need to place spire.xls.js and its corresponding .wasm file in your project's public directory (e.g., public/) so that they can be dynamically loaded in the browser. If your build tool is Webpack, remember to use webpackIgnore: true to prevent the resources from being incorrectly bundled.

In React, we asynchronously load the WASM module inside useEffect and mount its instance on window for global use. The core loading logic is as follows:

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;
Enter fullscreen mode Exit fullscreen mode

Here we specify the lookup path for the .wasm file to ensure all resources are loaded correctly. After a successful load, we can access the core Excel processing API via window.wasmModule.spirexls.

3. Basic Conversion Workflow

Converting an Excel file to PDF requires only a few core steps: load fonts and files into the virtual file system (VFS), create a Workbook object, perform the conversion, and export the download. Below is a complete React component that implements the entire process from module loading to triggering the download:


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);
      }
    })();
  }, []);

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

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

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

      // 3. Load the input Excel file into the virtual file system (VFS)
      const inputFileName = 'ToPDF.xlsx';
      await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

      // 4. Create a Workbook object and load the document
      const workbook = new wasmModule.Workbook();
      workbook.LoadFromFile({ fileName: inputFileName });

      // 5. Set conversion options (fit worksheets to one page)
      workbook.ConverterSetting.SheetFitToPage = true;

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

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

      // 8. Create a download link and trigger 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);

      // 9. Release resources
      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;
Enter fullscreen mode Exit fullscreen mode

Step‑by‑step explanation:

  1. Load fonts and the file to be converted into the VFS Spire.XLS relies on system fonts to render text, so we need to load the required TrueType font (e.g., Arial.ttf) into the /Library/Fonts/ directory of the VFS. Similarly, the input Excel file also needs to be stored in the VFS via FetchFileToVFS.
  2. Create a Workbook object and load the Excel file The Workbook class represents the entire Excel document. We load the source file we just stored using LoadFromFile.
  3. Set conversion options (optional) For example, set SheetFitToPage to true so that each worksheet fits onto one page.
  4. Save as PDF Call SaveToFile and specify the format as wasmModule.FileFormat.PDF.
  5. Read the generated PDF and trigger the download Use FS.readFile to obtain the PDF binary data from the VFS, create a Blob object, and then generate a download link using URL.createObjectURL.
  6. Release resources Call workbook.Dispose() to free memory.

The steps above are fully implemented in the ExcelToPDF function in the example code. After clicking the button, the user can download the converted PDF file.

4. More Control: Customising Your PDF Output

In real‑world business scenarios, we often need more than a "one‑click conversion"; we require fine‑grained control over the conversion result. Spire.XLS provides a wealth of configuration interfaces. Here are four common customisation methods.

1. Convert Specific Worksheets (Sheets)

By default, workbook.SaveToFile converts all worksheets. If you only need to output a specific page, you can use the Worksheet.SaveToPdf method instead:

// Get the first worksheet (index starts from 0)
let sheet = workbook.Worksheets.get(0);
// Save only that worksheet as PDF
sheet.SaveToPdf({ fileName: outputFileName });
Enter fullscreen mode Exit fullscreen mode

This is very useful when you only need a report summary or a particular data page.

2. Fit Each Worksheet to One Page

When a worksheet contains a lot of content, direct export may result in multiple pages or clipped content. With ConverterSetting, you can enable the "fit to page" feature with one line:

workbook.ConverterSetting.SheetFitToPage = true;
Enter fullscreen mode Exit fullscreen mode

This setting scales the worksheet content as a whole, ensuring that all columns and rows fit exactly onto one page – ideal for generating overview‑type PDFs.

3. Adjust Margins

PDF margins affect the final layout aesthetics. Spire.XLS allows you to set the top, bottom, left, and right margins (in inches) individually:

let sheet = workbook.Worksheets.get(0);
sheet.PageSetup.TopMargin = 0.5;
sheet.PageSetup.BottomMargin = 0.5;
sheet.PageSetup.LeftMargin = 0.3;
sheet.PageSetup.RightMargin = 0.3;
Enter fullscreen mode Exit fullscreen mode

Reasonable margin adjustments prevent content from sticking to the edges and improve the reading experience.

4. Specify Page Size

Different use cases require different page sizes – for example, contracts often use A4, while posters may require A3. You can easily switch via the PaperSize property:

sheet.PageSetup.PaperSize = wasmModule.PaperSizeType.PaperA3;
Enter fullscreen mode Exit fullscreen mode

Besides A3, the library also supports common paper types such as A4, A5, Letter, Legal, etc., allowing flexible choices based on your needs.

5. Complete Example and Important Notes

The React component App provided in this article already integrates all the above functionality. You only need to place the prepared font file (.ttf) and a sample Excel file (.xlsx) in the public/static/font/ and public/static/data/ directories respectively, and you can run it and try it out.

Key considerations:

  • Font loading : If garbled text or blank areas appear in the PDF, it is most likely due to missing fonts. Ensure that the loaded font supports the character sets used in the Excel file.
  • WASM loading : Because the WASM file is relatively large, the first load may take a few seconds. It is recommended to show a loading state in the UI.
  • File paths : The third parameter of FetchFileToVFS is the URL path of the source file on the server – make sure it is accessible.
  • Memory management : Always call Dispose() after processing a document to avoid memory leaks, especially in scenarios with frequent conversions.

6. Conclusion

With Spire.XLS for JavaScript, we have moved the traditionally complex, backend‑dependent Excel‑to‑PDF task entirely to the front end, reducing server load and improving user experience. From loading the module, basic conversion, to advanced controls, this article provides you with a complete practical solution. You can extend it further – for example, by adding file upload interfaces, supporting batch conversion, or integrating watermarks.

As WebAssembly technology continues to mature, front‑end document processing capabilities will become even more powerful. Spire.XLS has already paved the way for us. Now, go ahead and give it a try!

Top comments (0)