Table des matières
Installer via npm
npm i spire.pdf
Liens connexes
La conversion de PDF en HTML dans une application React permet aux utilisateurs de transformer des documents statiques en contenu web dynamique et accessible. Cette approche améliore la réactivité sur tous les appareils, simplifie les mises à jour de contenu et s'intègre directement aux pages web, éliminant ainsi le recours à des visualiseurs PDF externes. Elle préserve la mise en page d'origine tout en exploitant les fonctionnalités web natives, telles que les mises à jour d'interface utilisateur pilotées par l'état. En alliant la structure des PDF à la flexibilité des interfaces web modernes, cette méthode crée un contenu à la fois adaptable et convivial, sans compromettre l'intégrité du design.
Dans cet article, nous explorons comment utiliser Spire.PDF pour JavaScript pour convertir des fichiers PDF en HTML avec JavaScript dans une application React.
- Étapes pour convertir un PDF en HTML à l'aide de JavaScript
- Convertir un document PDF en un seul fichier HTML
- Convertir un PDF en HTML sans incorporer d'images
- Convertir des PDF en fichiers HTML séparés
- Optimiser la taille du fichier HTML converti
Installer et configurer Spire.PDF pour JavaScript dans votre application React
Pour commencer à convertir des PDF en HTML dans votre application React, suivez ces étapes :
1. Installer via npm:
Exécutez la commande suivante dans le répertoire racine de votre projet :
npm install spire.pdf
(Vous pouvez également télécharger Spire.PDF pour JavaScript depuis notre site Web.)
2. Ajoutez les fichiers requis :
Copiez les fichiers Spire.Pdf.Base.js et Spire.Pdf.Base.wasm dans le dossier public de votre projet. Cela garantit l'initialisation correcte du module WebAssembly.
3. Inclure les fichiers de polices :
Placez les fichiers de polices nécessaires dans le dossier désigné (par exemple, /public/fonts) pour garantir un rendu de texte précis et cohérent.
Pour plus de détails, veuillez consulter notre documentation : Comment intégrer Spire.PDF pour JavaScript dans un projet React
Étapes pour convertir un PDF en HTML à l'aide de JavaScript
Spire.PDF pour JavaScript inclut un module WebAssembly pour le traitement des documents PDF. En récupérant les PDF dans le système de fichiers virtuel (VFS), les développeurs peuvent les charger dans un objet PdfDocument et les convertir en différents formats, comme HTML. Les principales étapes sont les suivantes :
- Chargez le fichier Spire.Pdf.Base.js pour initialiser le module WebAssembly.
- Récupérez le fichier PDF sur le VFS à l'aide de la méthode wasmModule.FetchFileToVFS() .
- Récupérez les fichiers de polices utilisés dans le document PDF dans le dossier « /Library/Fonts/ » du VFS à l'aide de la méthode wasmModule.FetchFileToVFS() .
- Créez une instance de la classe PdfDocument à l'aide de la méthode wasmModule.PdfDocument.Create() .
- (Facultatif) Configurez les options de conversion à l'aide de la méthode PdfDocument.ConvertOptions.SetPdfToHtmlOptions() .
- Convertissez le document PDF au format HTML et enregistrez-le sur le VFS à l'aide de la méthode PdfDocument.SaveToFile() .
- Lisez et téléchargez le fichier HTML ou utilisez-le selon vos besoins.
Lors de la configuration des options de conversion à l'aide de la méthode PdfDocument.ConvertOptions.SetPdfToHtmlOptions() , les paramètres suivants peuvent être définis :
| Paramètre | Description |
| useEmbeddedSvg: bool | Incorpore les SVG dans le fichier HTML résultant. |
| useEmbeddedImg: bool | Incorpore les images au format SVG dans le fichier HTML résultant (nécessite que useEmbeddedSvg soit vrai). |
| maxPageOneFile: int | Spécifie le nombre maximal de pages PDF contenues dans un fichier HTML (effectif lorsque useEmbeddedSvg est vrai). |
| useHighQualityEmbeddedSvg: bool | Incorpore des SVG de haute qualité au fichier HTML. Cela affecte la qualité de l'image et la taille du fichier (effectif lorsque useEmbeddedSvg est défini sur true). |
Convertir un document PDF en un seul fichier HTML
En intégrant des SVG et des images et en définissant le nombre maximal de pages par fichier sur le nombre total de pages du PDF ou sur 0, les développeurs peuvent convertir un document PDF entier en un seul fichier HTML. Ils peuvent également convertir le PDF sans configurer aucune option, ce qui permet d'intégrer tous les éléments au fichier HTML avec des SVG de haute qualité.
Vous trouverez ci-dessous un exemple de code montrant comment convertir un document PDF en un seul fichier HTML à l'aide de Spire.PDF pour 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 un PDF en HTML sans incorporer d'images
Pour séparer le corps HTML des images et faciliter leur édition individuelle, les développeurs peuvent convertir des PDF en HTML sans intégrer d'images ni de SVG. Pour cela, il faut définir les paramètres useEmbeddedSvg et useEmbeddedImg sur false.
Vous trouverez ci-dessous un exemple de code illustrant cette conversion et son résultat :
- 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 des PDF en fichiers HTML séparés
Au lieu de convertir toutes les pages PDF en un seul fichier HTML, les développeurs peuvent définir le paramètre maxPageOneFile pour générer plusieurs fichiers HTML, chacun contenant un nombre limité de pages. Pour que cela fonctionne, useEmbeddedSvg et useEmbeddedImg doivent être définis sur true.
Voici un exemple de code illustrant cette conversion et son effet :
- 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

Optimiser la taille du fichier HTML converti
Lors de l'intégration de SVG dans le fichier HTML converti, les développeurs peuvent optimiser la taille du fichier en réduisant la qualité des SVG intégrés grâce au paramètre useHighQualityEmbeddedSvg . Notez que ce paramètre n'affecte que les SVG intégrés.
Voici un exemple de code illustrant cette optimisation et son effet :
- 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;

Demander une licence gratuite
Spire.PDF pour JavaScript propose une licence d'essai gratuite pour les entreprises et les particuliers. Vous pouvez demander une licence temporaire pour convertir des documents PDF en HTML sans restriction d'utilisation ni filigrane.
Si vous rencontrez des problèmes lors de la conversion, une assistance technique est disponible sur le forum Spire.PDF .
Conclusion
Convertir des PDF en HTML dans votre application React avec Spire.PDF pour JavaScript transforme les documents statiques en contenu web dynamique et accessible. Grâce à une installation simple de npm, une configuration adéquate des fichiers JavaScript, WASM et de polices, et à de multiples options de conversion (sortie en fichier unique, pages séparées et images non intégrées), vous pouvez préserver la fidélité de la mise en page tout en bénéficiant de fonctionnalités web modernes comme les mises à jour d'interface utilisateur pilotées par l'état.
Pour une personnalisation avancée, assurez-vous de consulter la documentation .