Trasforma i PDF in HTML interattivo in React con JavaScript

2025-03-25 06:49:02 Koohji

La conversione di PDF in HTML all'interno di un'applicazione React consente agli utenti di trasformare documenti statici in contenuti web dinamici e accessibili. Questo approccio migliora la reattività tra i dispositivi, semplifica gli aggiornamenti dei contenuti e si integra direttamente nelle pagine web, eliminando la necessità di visualizzatori PDF esterni. Mantiene il layout originale sfruttando al contempo funzionalità native del web come gli aggiornamenti dell'interfaccia utente basati sullo stato. Unendo la struttura dei PDF alla flessibilità delle moderne interfacce web, questo metodo crea contenuti adattabili e intuitivi senza compromettere l'integrità del design.

In questo articolo esploreremo come utilizzare Spire.PDF per JavaScript per convertire i file PDF in HTML con JavaScript in un'applicazione React .

Installa e configura Spire.PDF per JavaScript nella tua app React

Per iniziare a convertire i PDF in HTML nella tua applicazione React, segui questi passaggi:

1. Installa tramite npm:

Esegui il seguente comando nella directory principale del tuo progetto:

npm install spire.pdf

(In alternativa, è possibile scaricare Spire.PDF per JavaScript dal nostro sito web.)

2. Aggiungere i file richiesti:

Copia i file Spire.Pdf.Base.js e Spire.Pdf.Base.wasm nella cartella pubblica del tuo progetto. Questo assicura che il modulo WebAssembly venga inizializzato correttamente.

3. Includere i file dei font:

Inserire i file dei font necessari nella cartella designata (ad esempio, /public/fonts) per garantire una resa del testo accurata e coerente.

Per maggiori dettagli, fare riferimento alla nostra documentazione: Come integrare Spire.PDF per JavaScript in un progetto React

Passaggi per convertire PDF in HTML utilizzando JavaScript

Spire.PDF per JavaScript include un modulo WebAssembly per l'elaborazione di documenti PDF. Recuperando i PDF nel file system virtuale (VFS), gli sviluppatori possono caricarli in un oggetto PdfDocument e convertirli in vari formati come HTML. I passaggi principali sono i seguenti:

  • Caricare il file Spire.Pdf.Base.js per inizializzare il modulo WebAssembly.
  • Recupera il file PDF sul VFS utilizzando il metodo wasmModule.FetchFileToVFS() .
  • Recupera i file dei font utilizzati nel documento PDF nella cartella "/Library/Fonts/" nel VFS utilizzando il metodo wasmModule.FetchFileToVFS() .
  • Creare un'istanza della classe PdfDocument utilizzando il metodo wasmModule.PdfDocument.Create() .
  • (Facoltativo) Configurare le opzioni di conversione utilizzando il metodo PdfDocument.ConvertOptions.SetPdfToHtmlOptions() .
  • Convertire il documento PDF in formato HTML e salvarlo nel VFS utilizzando il metodo PdfDocument.SaveToFile() .
  • Leggi e scarica il file HTML oppure utilizzalo secondo necessità.

Quando si configurano le opzioni di conversione utilizzando il metodo PdfDocument.ConvertOptions.SetPdfToHtmlOptions() , è possibile impostare i seguenti parametri:

Parametro Descrizione
useEmbeddedSvg: bool Incorpora gli SVG nel file HTML risultante.
useEmbeddedImg: bool Incorpora le immagini come SVG nel file HTML risultante (richiede che useEmbeddedSvg sia true).
maxPageOneFile: int Specifica il numero massimo di pagine PDF contenute in un file HTML (efficace quando useEmbeddedSvg è true).
useHighQualityEmbeddedSvg: bool Incorpora SVG di alta qualità nel file HTML. Ciò influisce sia sulla qualità dell'immagine che sulle dimensioni del file (efficace quando useEmbeddedSvg è true).

Convertire un documento PDF in un singolo file HTML

Incorporando SVG e immagini e impostando il numero massimo di pagine per file sul numero totale di pagine del PDF o su 0, gli sviluppatori possono convertire un intero documento PDF in un singolo file HTML. In alternativa, gli sviluppatori possono convertire il PDF senza configurare alcuna opzione, il che si traduce nell'incorporamento di tutti gli elementi nel file HTML con SVG di alta qualità.

Di seguito è riportato un esempio di codice che mostra come convertire un documento PDF in un singolo file HTML utilizzando Spire.PDF per 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;

Convertire un documento PDF in un singolo file HTML

Converti PDF in HTML senza incorporare immagini

Per separare il corpo HTML dalle immagini per una più facile modifica individuale, gli sviluppatori possono convertire i PDF in HTML senza incorporare immagini e SVG. Ciò richiede di impostare i parametri useEmbeddedSvguseEmbeddedImg su false.

Di seguito è riportato un esempio di codice che dimostra questa conversione e il suo risultato:

  • 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;

Converti PDF in HTML senza incorporare immagini

Converti PDF in file HTML separati

Invece di convertire tutte le pagine PDF in un singolo file HTML, gli sviluppatori possono impostare il parametro maxPageOneFile per generare più file HTML, ognuno contenente un numero limitato di pagine. Per farlo funzionare, useEmbeddedSvguseEmbeddedImg devono essere impostati su true.

Di seguito è riportato un esempio di codice che dimostra questa conversione e il suo effetto:

  • 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
        

Converti PDF in file HTML separati

Ottimizzare le dimensioni dei file del file HTML convertito

Quando si incorporano SVG nel file HTML convertito, gli sviluppatori possono ottimizzare le dimensioni del file abbassando la qualità degli SVG incorporati utilizzando il parametro useHighQualityEmbeddedSvg . Nota che questo parametro riguarda solo gli SVG incorporati.

Di seguito è riportato un esempio di codice che dimostra questa ottimizzazione e il suo effetto:

  • 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;

Ottimizzare le dimensioni dei file del file HTML convertito

Richiedi una licenza gratuita

Spire.PDF per JavaScript offre una licenza di prova gratuita sia per utenti aziendali che individuali. Puoi richiedere una licenza temporanea per convertire documenti PDF in HTML senza restrizioni di utilizzo o filigrane.

Se riscontri problemi durante la conversione, puoi usufruire del supporto tecnico sul forum Spire.PDF .

Conclusione

La conversione di PDF in HTML nella tua app React con Spire.PDF per JavaScript trasforma i documenti statici in contenuti web dinamici e accessibili. Con una semplice installazione di npm, la corretta configurazione di JavaScript, WASM e file di font e più opzioni di conversione, tra cui output a file singolo, pagine separate e immagini non incorporate, puoi preservare la fedeltà del layout sbloccando al contempo funzionalità web moderne come gli aggiornamenti dell'interfaccia utente basati sullo stato.

Per personalizzazioni avanzate, assicurati di consultare la documentazione .

See Also