Converting PDF files to Word documents is essential for modern web applications focused on document management and editing. Using JavaScript and React, developers can easily integrate this functionality with libraries like Spire.PDF for JavaScript. This guide will walk you through implementing a PDF-to-Word conversion feature in a React application, showing how to load files, configure settings, and enable users to download their converted documents effortlessly.
Install Spire.PDF for JavaScript
To get started with converting PDF to Word with JavaScript in a React application, you can either download Spire.PDF for JavaScript from our website or install it via npm with the following command:
npm i spire.pdf
After that, copy the "Spire.Pdf.Base.js" and "Spire.Pdf.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.PDF for JavaScript in a React Project
Convert PDF to Word Using PdfToDocConverter Class
The PdfToDocConverter class from Spire.PDF for JavaScript facilitates the conversion of PDF files to Word documents. It includes the DocxOptions property, allowing developers to customize conversion settings, including document properties. The conversion is performed using the SaveToDocx() method.
Steps to convert PDF to Word using the PdfToDocConverter class in React:
- Load the necessary font files and input PDF file into the virtual file system (VFS).
- Instantiate a PdfToDocConverter object using the wasmModule.PdfToDocConverter.Create() method, passing the PDF file path.
- Customize the generated Word file's properties using the DocxOptions property.
- Use the SaveToDocx() method to convert the PDF document.
- Trigger the download of the resulting Word file.
- 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 spirepdf from the global window object const { Module, spirepdf } = window; // Set the wasmModule state when the runtime is initialized Module.onRuntimeInitialized = () => { setWasmModule(spirepdf); }; } 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.Pdf.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert PDF to Word const ConvertPdfToWord = async () => { if (wasmModule) { // Load the necessary font files into the virtual file system (VFS) await wasmModule.FetchFileToVFS('GOTHIC.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICB.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICBI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); // Load the input PDF file into the VFS let inputFileName = 'input.pdf'; await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create a PdfToDocConverter object let converter = wasmModule.PdfToDocConverter.Create({filePath: inputFileName}); // Set document properties of the generated Word file converter.DocxOptions.Subject = "Convert PDF to Word"; converter.DocxOptions.Authors = "E-ICEBLUE" // Define the output file name const outputFileName = "ToWord.docx"; // Convert PDF as a Docx file converter.SaveToDocx({fileName: outputFileName}); // Read the generated Word file const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Create a Blob object from the Word file const modifiedFile = new Blob([modifiedFileArray], {type:'msword'}); // Create a URL for the Blob const url = URL.createObjectURL(modifiedFile); // Create an anchor element to trigger the download const a = document.createElement('a'); a.href = url; a.download = outputFileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Convert PDF to Word in React</h1> <button onClick={ConvertPdfToWord} 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.
Below is a screenshot showing the input PDF file and the output Word file:
Convert PDF to Word Using PdfDocument Class
To convert PDF to Word, you can also use the PdfDocument class. This class allows developers to load an existing PDF document, make modifications, and save it as a Word file. This feature is particularly useful for users who need to edit or enhance their PDFs before conversion.
Steps to convert PDF to Word Using the PdfDocument class in React:
- Load the necessary font files and input PDF file into the virtual file system (VFS).
- Create a PdfDocument object using the wasmModule.PdfDocument.Create() method
- Load the PDF document using the PdfDocument.LoadFromFile() method.
- Convert the PDF document to a Word file using the PdfDocument.SaveToFile() method.
- Trigger the download of the resulting Word file.
- 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 spirepdf from the global window object const { Module, spirepdf } = window; // Set the wasmModule state when the runtime is initialized Module.onRuntimeInitialized = () => { setWasmModule(spirepdf); }; } 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.Pdf.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert PDF to Word const ConvertPdfToWord = async () => { if (wasmModule) { // Load the necessary font files into the virtual file system (VFS) await wasmModule.FetchFileToVFS('GOTHIC.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICB.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICBI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('GOTHICI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); // Load the input PDF file into the VFS let inputFileName = 'input.pdf'; await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Create a PdfDocument object let doc = wasmModule.PdfDocument.Create(); // Load the PDF file doc.LoadFromFile(inputFileName); // Define the output file name const outputFileName = "ToWord.docx"; // Convert PDF as a Docx file doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.DOCX}); // Read the generated Word file const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Create a Blob object from the Word file const modifiedFile = new Blob([modifiedFileArray], {type:'msword'}); // Create a URL for the Blob const url = URL.createObjectURL(modifiedFile); // Create an anchor element to trigger the download const a = document.createElement('a'); a.href = url; a.download = outputFileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); // Cleanup resources doc.Dispose(); } }; return ( <div style={{ textAlign: 'center', height: '300px' }}> <h1>Convert PDF to Word in React</h1> <button onClick={ConvertPdfToWord} disabled={!wasmModule}> Convert </button> </div> ); } export default App;
Get a Free License
To fully experience the capabilities of Spire.PDF for JavaScript without any evaluation limitations, you can request a free 30-day trial license.