In modern web development, generating PDFs directly from HTML is essential for applications requiring dynamic reports, invoices, or user-specific documents. Using JavaScript to convert HTML to PDF in React applications ensures the preservation of structure, styling, and interactivity, transforming content into a portable, print-ready format. This method eliminates the need for separate PDF templates, leverages React's component-based architecture for dynamic rendering, and reduces server-side dependencies. By embedding PDF conversion into the front end, developers can provide a consistent user experience, enable instant document downloads, and maintain full control over design and layout. This article explores how to use Spire.Doc for JavaScript to convert HTML files and strings to PDF in React applications.
Install Spire.Doc for JavaScript
To get started with converting HTML 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:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files into the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Convert an HTML File to PDF with JavaScript
Using the Spire.Doc WASM module, developers can load HTML files into a Document object with the Document.LoadFromFile() method and then convert them to PDF documents using the Document.SaveToFile() method. This approach provides a concise and efficient solution for HTML-to-PDF conversion in web development.
The detailed steps are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Load the HTML file and the font files used in the HTML file into the virtual file system using the wasmModule.FetchFileToVFS() method.
- Create an instance of the Document class using the wasmModule.Document.Create() method.
- Load the HTML file into the Document instance using the Document.LoadFromFile() method.
- Convert the HTML file to PDF format and save it using the Document.SaveToFile() method.
- Read the converted file as a file array and download it.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the WASM module:', err); } }; // Create a script element to load the WASM JavaScript file const script = document.createElement('script'); script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert HTML files to PDF document const ConvertHTMLFileToPDF = async () => { if (wasmModule) { // Specify the input and output file names const inputFileName = 'Sample.html'; const outputFileName = 'HTMLFileToPDF.pdf'; // Fetch the input file and add it to the VFS await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`); // Fetch the font file and add it to the VFS await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); await wasmModule.FetchFileToVFS('Georgia.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); // Create an instance of the Document class const doc = wasmModule.Document.Create(); // Load the Word document doc.LoadFromFile({ fileName: inputFileName, fileFormat: wasmModule.FileFormat.Html, validationType: wasmModule.XHTMLValidationType.None }); // Save the document to a PDF file doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF }); // Release resources doc.Dispose(); // Read the saved file from the VFS const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Generate a Blob from the file array and trigger a download const blob = new Blob([modifiedFileArray], {type: 'application/pdf'}); const url = URL.createObjectURL(blob); 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 (); } export default App;Convert HTML Files to PDF Using JavaScript in React
Convert an HTML String to PDF with JavaScript
Spire.Doc for JavaScript offers the Paragraph.AppendHTML() method, which allows developers to insert HTML-formatted content directly into a document paragraph. Once the HTML content is added, the document can be saved as a PDF, enabling a seamless conversion from an HTML string to a PDF file.
The detailed steps are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Define the HTML string.
- Load the font files used in the HTML string using the wasmModule.FetchFileToVFS() method.
- Create a new Document instance using the wasmModule.Document.Create() method.
- Add a section to the document using the Document.AddSection() method.
- Add a paragraph to the section using the Section.AddParagraph() method.
- Insert the HTML content into the paragraph using the Paragraph.AppendHTML() method.
- Save the document as a PDF file using the Document.SaveToFile() method.
- Read the converted file as a file array and download it.
- JavaScript
import React, { useState, useEffect } from 'react'; function App() { // State to store 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 module loading console.error('Failed to load the WASM module:', err); } }; // Create a script element to load the WASM JavaScript file const script = document.createElement('script'); script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`; script.onload = loadWasm; // Append the script to the document body document.body.appendChild(script); // Cleanup function to remove the script when the component unmounts return () => { document.body.removeChild(script); }; }, []); // Function to convert HTML string to PDF const ConvertHTMLStringToPDF = async () => { if (wasmModule) { // Specify the output file name const outputFileName = 'HTMLStringToPDF.pdf'; // Define the HTML string const htmlString = ` <html lang="en"> <head> <meta charset="UTF-8"> <title>Sales Snippet</title> </head> <body style="font-family: Arial, sans-serif; margin: 20px;"> <div style="border: 1px solid #ddd; padding: 15px; max-width: 600px; margin: auto; background-color: #f9f9f9;"> <h1 style="color: #e74c3c; text-align: center;">Limited Time Offer!</h1> <p style="font-size: 1.1em; color: #333; line-height: 1.5;"> Get ready to save big on all your favorites. This week only, enjoy 15% off site wide. From trendy clothing to home decor, find everything you love at unbeatable prices. </p> <div style="text-align: center;"> <button style="background-color: #5cb85c; border: none; color: white; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 8px;" > Shop Deals </button> </div> </div> </body> </html> `; // Fetch the font file and add it to the VFS await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`); // Create an instance of the Document class const doc = wasmModule.Document.Create(); // Add a section to the document const section = doc.AddSection(); // Add a paragraph to the section const paragraph = section.AddParagraph(); // Insert the HTML content to the paragraph paragraph.AppendHTML(htmlString) // Save the document to a PDF file doc.SaveToFile({fileName: outputFileName, fileFormat: wasmModule.FileFormat.PDF}); // Release resources doc.Dispose(); // Read the saved file from the VFS const modifiedFileArray = wasmModule.FS.readFile(outputFileName); // Generate a Blob from the file array and trigger a download const blob = new Blob([modifiedFileArray], {type: 'application/pdf'}); const url = URL.createObjectURL(blob); 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 HTML Strings to PDF Using JavaScript in React</h1> <button onClick={ConvertHTMLStringToPDF} disabled={!wasmModule}> Convert and Download </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.