DEV Community

jelizaveta
jelizaveta

Posted on

How to Convert Word to PDF in JavaScript (Complete Guide)

In modern web applications, document processing capabilities are increasingly becoming essential. Whether generating reports, exporting contracts, or processing user-uploaded documents, Word-to-PDF conversion is one of the most common requirements. This article explores how to achieve high-quality Word to PDF conversion in React applications using the Spire.Doc for JavaScript library.

Why Choose Spire.Doc for JavaScript?

There are many options for document conversion on the front end, but Spire.Doc for JavaScript offers several standout advantages:

  • No backend server required : All conversion happens on the client side, protecting user data privacy
  • High-quality rendering : Perfectly preserves the original document's formatting, fonts, and layout
  • Rich feature support : Not only supports conversion but also creating, editing, and manipulating Word documents
  • Cross-platform compatibility : Built on WebAssembly, runs smoothly in major browsers

Project Initialization

First, install Spire.Office in your React project:

npm i spire.office
Enter fullscreen mode Exit fullscreen mode

Core Implementation Breakdown

1. Loading the WASM Module

Spire.Doc runs on WebAssembly and requires loading the core module first. Here, React's useEffect is used to load it asynchronously when the component mounts:

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);
    }
  })();
}, []);
Enter fullscreen mode Exit fullscreen mode

Key points explained:

  • webpackIgnore: true ensures webpack does not process this dynamic import, avoiding resource path errors
  • The locateFile function specifies the loading path for WASM files
  • After successful module loading, it's stored in state to control button availability

2. Font Management

Fonts are the most common point of failure in document conversion. Spire.Doc needs fonts loaded into the virtual file system (VFS) to ensure correct PDF rendering:

// Load Times New Roman font family
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/`);
Enter fullscreen mode Exit fullscreen mode

Best practices:

  • Place commonly used font files in the public/static/font/ directory
  • Selectively load fonts based on those actually used in the document to reduce load time
  • For Chinese documents, Chinese fonts (such as SimSun, SimHei, etc.) need to be loaded

3. Document Conversion Core Workflow

The complete conversion process includes the following steps:

// 1. Load Word document into VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);

// 2. Create Document instance and load the document
const doc = new wasmModule.Document();
doc.LoadFromFile(inputFileName);

// 3. Configure conversion parameters
let parameters = new wasmModule.ToPdfParameterList();
parameters.IsEmbeddedAllFonts = true;  // Embed all fonts for consistent display across devices

// 4. Execute conversion and save
const outputFileName = 'ToPDF.pdf';
doc.SaveToFile({ fileName: outputFileName, paramList: parameters });

// 5. Read the generated file
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/pdf' });
Enter fullscreen mode Exit fullscreen mode

4. File Download and Resource Cleanup

After generating the PDF, create a download link and clean up resources:

// Create download
const url = URL.createObjectURL(modifiedFile);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();

// Clean up resources
document.body.removeChild(a);
URL.revokeObjectURL(url);
doc.Dispose();  // Release document object
Enter fullscreen mode Exit fullscreen mode

Complete Component Example

Combining all the above steps gives us the complete React component:

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

function App() {
  const [wasmModule, setWasmModule] = useState(null);

  useEffect(() => {
    // WASM loading logic...
  }, []);

  const convertWordToPdf = async () => {
    // Conversion logic...
  };

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

Performance Optimization Recommendations

  1. Font caching : Cache commonly used fonts in IndexedDB to avoid repeated loading
  2. Progress indicators : Use loading animations or progress bars for large file conversions to improve user experience
  3. Error handling : Comprehensive try-catch blocks with user-friendly error messages
  4. Memory management : Call Dispose() promptly after conversion to release resources

Common Issues and Solutions

Q: Converted PDF shows garbled Chinese text?
A: Ensure the corresponding Chinese font files are loaded and set IsEmbeddedAllFonts = true in the conversion parameters.

Q: WASM module fails to load?
A: Check that spire.doc.js and spire.doc.wasm exist in the public directory and that the path configuration is correct.

Q: Browser freezes when converting large files?
A: Use Web Workers to offload the conversion task to a background thread.

Summary

With Spire.Doc for JavaScript, we can achieve professional-grade Word to PDF conversion entirely in a front-end environment. The solution provided in this article is not only concise in code but also includes best practices for font management, error handling, and resource cleanup, ready for production deployment.

This client-side conversion approach is particularly suitable for:

  • Enterprise applications that need to protect data privacy
  • Offline-first web applications
  • Scenarios where reducing server load is desired

We hope this article helps you successfully implement document conversion functionality in your projects. If you have any questions or suggestions, feel free to discuss in the comments!

Top comments (0)