Tabla de contenido
Instalar mediante npm
npm i spire.pdf
Enlaces relacionados
La conversión de PDF a HTML dentro de una aplicación React permite a los usuarios transformar documentos estáticos en contenido web dinámico y accesible. Este enfoque mejora la capacidad de respuesta en diferentes dispositivos, simplifica las actualizaciones de contenido y se integra directamente en las páginas web, eliminando la necesidad de visores de PDF externos. Conserva el diseño original a la vez que aprovecha las funciones nativas de la web, como las actualizaciones de la interfaz de usuario basadas en el estado. Al combinar la estructura de los PDF con la flexibilidad de las interfaces web modernas, este método crea contenido adaptable e intuitivo sin comprometer la integridad del diseño.
En este artículo, exploramos cómo usar Spire.PDF para JavaScript para convertir archivos PDF a HTML con JavaScript en una aplicación React.
- Pasos para convertir PDF a HTML usando JavaScript
- Convertir un documento PDF en un único archivo HTML
- Convertir PDF a HTML sin incrustar imágenes
- Convertir PDF a archivos HTML separados
- Optimizar el tamaño de los archivos HTML convertidos
Instalar y configurar Spire.PDF para JavaScript en su aplicación React
Para comenzar a convertir archivos PDF a HTML en su aplicación React, siga estos pasos:
1. Instalar mediante npm:
Ejecute el siguiente comando en el directorio raíz de su proyecto:
npm install spire.pdf
(Alternativamente, puede descargar Spire.PDF para JavaScript desde nuestro sitio web).
2. Agregue los archivos necesarios:
Copia los archivos Spire.Pdf.Base.js y Spire.Pdf.Base.wasm en la carpeta pública de tu proyecto. Esto garantiza que el módulo WebAssembly se inicialice correctamente.
3. Incluir archivos de fuentes:
Coloque los archivos de fuentes necesarios en la carpeta designada (por ejemplo, /public/fonts) para garantizar una representación del texto precisa y consistente.
Para obtener más detalles, consulte nuestra documentación: Cómo integrar Spire.PDF para JavaScript en un proyecto React
Pasos para convertir PDF a HTML usando JavaScript
Spire.PDF para JavaScript incluye un módulo WebAssembly para procesar documentos PDF. Al importar los PDF al sistema de archivos virtual (VFS), los desarrolladores pueden cargarlos en un objeto PdfDocument y convertirlos a diversos formatos, como HTML. Los pasos principales son los siguientes:
- Cargue el archivo Spire.Pdf.Base.js para inicializar el módulo WebAssembly.
- Obtenga el archivo PDF en el VFS utilizando el método wasmModule.FetchFileToVFS() .
- Obtenga los archivos de fuentes utilizados en el documento PDF en la carpeta "/Library/Fonts/" en el VFS usando el método wasmModule.FetchFileToVFS() .
- Cree una instancia de la clase PdfDocument utilizando el método wasmModule.PdfDocument.Create() .
- (Opcional) Configure las opciones de conversión utilizando el método PdfDocument.ConvertOptions.SetPdfToHtmlOptions() .
- Convierta el documento PDF al formato HTML y guárdelo en el VFS utilizando el método PdfDocument.SaveToFile() .
- Lea y descargue el archivo HTML o úselo según sea necesario.
Al configurar las opciones de conversión mediante el método PdfDocument.ConvertOptions.SetPdfToHtmlOptions() , se pueden configurar los siguientes parámetros:
| Parámetro | Descripción |
| useEmbeddedSvg: bool | Incrusta SVG en el archivo HTML resultante. |
| useEmbeddedImg: bool | Incrusta imágenes como SVG en el archivo HTML resultante (requiere que useEmbeddedSvg sea verdadero). |
| maxPageOneFile: int | Especifica el número máximo de páginas PDF contenidas en un archivo HTML (efectivo cuando useEmbeddedSvg es verdadero). |
| useHighQualityEmbeddedSvg: bool | Incrusta SVG de alta calidad en el archivo HTML. Esto afecta tanto la calidad de la imagen como el tamaño del archivo (efectivo cuando useEmbeddedSvg es verdadero). |
Convertir un documento PDF en un único archivo HTML
Al incrustar archivos SVG e imágenes y establecer el número máximo de páginas por archivo en el total de páginas del PDF o en 0, los desarrolladores pueden convertir un documento PDF completo en un solo archivo HTML. Como alternativa, pueden convertir el PDF sin configurar ninguna opción, lo que permite incrustar todos los elementos en el archivo HTML con archivos SVG de alta calidad.
A continuación se muestra un ejemplo de código que demuestra cómo convertir un documento PDF en un solo archivo HTML usando Spire.PDF para JavaScript:
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
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 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 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.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 HTML
const ConvertPDFToHTML = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFToHTML.html';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file used in the PDF to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('CalibriBold.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Convert the PDF document to an HTML file
pdf.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.HTML});
// Set the conversion options (optional)
pdf.ConvertOptions.SetPdfToHtmlOptions({ useEmbeddedSvg: true, useEmbeddedImg: true, maxPageOneFile: pdf.Pages.Count, useHighQualityEmbeddedSvg: true})
// Read the HTML file from the VFS
const htmlArray = wasmModule.FS.readFile(outputFileName)
// Create a Blob from the HTML file and download it
const blob = new Blob([htmlArray], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = outputFileName;
link.click();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PDF to HTML Using JavaScript in React</h1>
<button onClick={ConvertPDFToHTML} disabled={!wasmModule}>
Convert and Download
</button>
</div>
);
}
export default App;

Convertir PDF a HTML sin incrustar imágenes
Para separar el cuerpo HTML de las imágenes y facilitar la edición individual, los desarrolladores pueden convertir archivos PDF a HTML sin incrustar imágenes ni SVG. Esto requiere configurar los parámetros useEmbeddedSvg y useEmbeddedImg como falsos.
A continuación se muestra un ejemplo de código que demuestra esta conversión y su resultado:
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
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 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 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.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 HTML
const ConvertPDFToHTML = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = '/output/PDFToHTML.html';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file used in the PDF to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('CalibriBold.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Set the conversion options to disable SVG and image embedding
pdf.ConvertOptions.SetPdfToHtmlOptions({ useEmbeddedSvg: false, useEmbeddedImg: false})
// Convert the PDF document to an HTML file
pdf.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.HTML});
// Create a new JSZip object
const zip = new JSZip();
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Add all files in the output folder to the ZIP
addFilesToZip('/output', zip);
// Generate and download the ZIP file
zip.generateAsync({ type: 'blob' }).then((content) => {
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = `PDFToHTML.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PDF to HTML Without Embedding Images Using JavaScript in React</h1>
<button onClick={ConvertPDFToHTML} disabled={!wasmModule}>
Convert and Download
</button>
</div>
);
}
export default App;

Convertir PDF a archivos HTML separados
En lugar de convertir todas las páginas PDF en un solo archivo HTML, los desarrolladores pueden configurar el parámetro maxPageOneFile para generar varios archivos HTML, cada uno con un número limitado de páginas. Para que esto funcione, useEmbeddedSvg y useEmbeddedImg deben estar configurados como verdaderos.
El siguiente es un ejemplo de código que demuestra esta conversión y su efecto:
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
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 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 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.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 HTML
const ConvertPDFToHTML = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = '/output/PDFToHTML.html';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file used in the PDF to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('CalibriBold.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Set the conversion options to disable SVG and image embedding
pdf.ConvertOptions.SetPdfToHtmlOptions({ useEmbeddedSvg: false, useEmbeddedImg: false, maxPageOneFile: 1 })
// Convert the PDF document to an HTML file
pdf.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.HTML});
// Create a new JSZip object
const zip = new JSZip();
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Add all files in the output folder to the ZIP
addFilesToZip('/output', zip);
// Generate and download the ZIP file
zip.generateAsync({ type: 'blob' }).then((content) => {
const url = URL.createObjectURL(content);
const a = document.createElement('a');
a.href = url;
a.download = `PDFToHTML.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
});
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PDF to HTML Without Embedding Images Using JavaScript in React
Convert and Download

Optimizar el tamaño de los archivos HTML convertidos
Al incrustar SVG en el archivo HTML convertido, los desarrolladores pueden optimizar el tamaño del archivo reduciendo la calidad de los SVG incrustados mediante el parámetro useHighQualityEmbeddedSvg . Tenga en cuenta que este parámetro solo afecta a los SVG incrustados.
El siguiente es un ejemplo de código que demuestra esta optimización y su efecto:
- 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 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 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.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 HTML
const ConvertPDFToHTML = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.pdf';
const outputFileName = 'PDFToHTML.html';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file used in the PDF to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('CalibriBold.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create an instance of the PdfDocument class
const pdf = wasmModule.PdfDocument.Create();
// Load the PDF document from the VFS
pdf.LoadFromFile(inputFileName);
// Set the conversion options to convert with lower quality embedded SVG
pdf.ConvertOptions.SetPdfToHtmlOptions({ useEmbeddedSvg: true, useEmbeddedImg: true, maxPageOneFile: 0, useHighQualityEmbeddedSvg: false })
// Convert the PDF document to an HTML file
pdf.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.HTML});
// Read the HTML file from the VFS
const htmlArray = wasmModule.FS.readFile(outputFileName)
// Create a Blob from the HTML file and download it
const blob = new Blob([htmlArray], { type: 'text/html' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = outputFileName;
link.click();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PDF to HTML Optimize File Size Using JavaScript in React</h1>
<button onClick={ConvertPDFToHTML} disabled={!wasmModule}>
Convert and Download
</button>
</div>
);
}
export default App;

Solicitar una licencia gratuita
Spire.PDF para JavaScript ofrece una licencia de prueba gratuita para empresas y particulares. Puede solicitar una licencia temporal para convertir documentos PDF a HTML sin restricciones de uso ni marcas de agua.
Si encuentra problemas durante la conversión, hay soporte técnico disponible en el foro Spire.PDF .
Conclusión
Convertir archivos PDF a HTML en tu aplicación React con Spire.PDF para JavaScript transforma documentos estáticos en contenido web dinámico y accesible. Con una sencilla instalación de npm, la configuración correcta de JavaScript, WASM y los archivos de fuentes, y múltiples opciones de conversión (incluyendo salida de un solo archivo, páginas separadas e imágenes no incrustadas), puedes conservar la fidelidad del diseño y, al mismo tiempo, acceder a funciones web modernas como las actualizaciones de la interfaz de usuario basadas en el estado.
Para una personalización avanzada, asegúrese de consultar la documentación .