Transforme PDFs em HTML interativo no React com JavaScript

2025-03-25 06:45:58 Koohji

Converter PDFs em HTML em um aplicativo React permite que os usuários transformem documentos estáticos em conteúdo da web dinâmico e acessível. Essa abordagem aprimora a capacidade de resposta em todos os dispositivos, simplifica as atualizações de conteúdo e integra-se diretamente às páginas da web, eliminando a necessidade de visualizadores de PDF externos. Ele preserva o layout original enquanto aproveita os recursos nativos da web, como atualizações de IU orientadas por estado. Ao mesclar a estrutura dos PDFs com a flexibilidade das interfaces da web modernas, esse método cria conteúdo adaptável e amigável ao usuário sem comprometer a integridade do design.

Neste artigo, exploramos como usar o Spire.PDF para JavaScript para converter arquivos PDF em HTML com JavaScript em um aplicativo React.

Instalar e configurar Spire.PDF para JavaScript em seu aplicativo React

Para começar a converter PDFs em HTML no seu aplicativo React, siga estas etapas:

1. Instalar via npm:

Execute o seguinte comando no diretório raiz do seu projeto:

npm install spire.pdf

(Alternativamente, você pode baixar o Spire.PDF para JavaScript em nosso site.)

2. Adicione os arquivos necessários:

Copie os arquivos Spire.Pdf.Base.js e Spire.Pdf.Base.wasm para a pasta pública do seu projeto. Isso garante que o módulo WebAssembly seja inicializado corretamente.

3. Incluir arquivos de fonte:

Coloque os arquivos de fonte necessários na pasta designada (por exemplo, /public/fonts) para garantir uma renderização de texto precisa e consistente.

Para mais detalhes, consulte nossa documentação: Como integrar Spire.PDF para JavaScript em um projeto React

Etapas para converter PDF em HTML usando JavaScript

O Spire.PDF para JavaScript inclui um módulo WebAssembly para processar documentos PDF. Ao buscar PDFs no sistema de arquivos virtual (VFS), os desenvolvedores podem carregá-los em um objeto PdfDocument e convertê-los em vários formatos, como HTML. As principais etapas são as seguintes:

  • Carregue o arquivo Spire.Pdf.Base.js para inicializar o módulo WebAssembly.
  • Busque o arquivo PDF no VFS usando o método wasmModule.FetchFileToVFS() .
  • Busque os arquivos de fonte usados ​​no documento PDF para a pasta "/Library/Fonts/" no VFS usando o método wasmModule.FetchFileToVFS() .
  • Crie uma instância da classe PdfDocument usando o método wasmModule.PdfDocument.Create() .
  • (Opcional) Configure as opções de conversão usando o método PdfDocument.ConvertOptions.SetPdfToHtmlOptions() .
  • Converta o documento PDF para o formato HTML e salve-o no VFS usando o método PdfDocument.SaveToFile() .
  • Leia e baixe o arquivo HTML ou use-o conforme necessário.

Ao configurar opções de conversão usando o método PdfDocument.ConvertOptions.SetPdfToHtmlOptions() , os seguintes parâmetros podem ser definidos:

Parâmetro Descrição
useEmbeddedSvg: bool Embeds SVGs in the resulting HTML file.
useEmbeddedImg: bool Incorpora imagens como SVGs no arquivo HTML resultante (requer que useEmbeddedSvg seja verdadeiro).
maxPageOneFile: int Especifica o número máximo de páginas PDF contidas em um arquivo HTML (efetivo quando useEmbeddedSvg é verdadeiro).
useHighQualityEmbeddedSvg: bool Incorpora SVGs de alta qualidade no arquivo HTML. Isso afeta tanto a qualidade da imagem quanto o tamanho do arquivo (efetivo quando useEmbeddedSvg é true).

Converter um documento PDF em um único arquivo HTML

Ao incorporar SVGs e imagens e definir o máximo de páginas por arquivo para a contagem total de páginas do PDF ou para 0, os desenvolvedores podem converter um documento PDF inteiro em um único arquivo HTML. Como alternativa, os desenvolvedores podem converter o PDF sem configurar nenhuma opção, o que resulta em todos os elementos sendo incorporados no arquivo HTML com SVGs de alta qualidade.

Abaixo está um exemplo de código demonstrando como converter um documento PDF em um único arquivo 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;

Converter um documento PDF em um único arquivo HTML

Converter PDF em HTML sem incorporar imagens

Para separar o corpo HTML das imagens para facilitar a edição individual, os desenvolvedores podem converter PDFs em HTML sem incorporar imagens e SVGs. Isso requer a configuração dos parâmetros useEmbeddedSvguseEmbeddedImg como false.

Abaixo está um exemplo de código demonstrando essa conversão e seu 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;

Converter PDF em HTML sem incorporar imagens

Converter PDF em arquivos HTML separados

Em vez de converter todas as páginas PDF em um único arquivo HTML, os desenvolvedores podem definir o parâmetro maxPageOneFile para gerar vários arquivos HTML, cada um contendo um número limitado de páginas. Para que isso funcione, useEmbeddedSvguseEmbeddedImg devem ser definidos como true.

A seguir está um exemplo de código demonstrando essa conversão e seu efeito:

  • 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
        

Converter PDF em arquivos HTML separados

Otimize o tamanho dos arquivos HTML convertidos

Ao incorporar SVGs no arquivo HTML convertido, os desenvolvedores podem otimizar o tamanho do arquivo reduzindo a qualidade dos SVGs incorporados usando o parâmetro useHighQualityEmbeddedSvg . Observe que esse parâmetro afeta apenas SVGs incorporados.

A seguir está um exemplo de código demonstrando essa otimização e seu efeito:

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

Otimize o tamanho dos arquivos HTML convertidos

Solicite uma licença gratuita

O Spire.PDF para JavaScript oferece uma licença de teste gratuita para usuários corporativos e individuais. Você pode solicitar uma licença temporária para converter documentos PDF para HTML sem nenhuma restrição de uso ou marca d'água.

Se você encontrar problemas durante a conversão, o suporte técnico está disponível no fórum Spire.PDF .

Conclusão

Converter PDFs em HTML no seu aplicativo React com Spire.PDF para JavaScript transforma documentos estáticos em conteúdo web dinâmico e acessível. Com uma instalação simples do npm, configuração adequada dos arquivos JavaScript, WASM e de fonte, e várias opções de conversão — incluindo saída de arquivo único, páginas separadas e imagens não incorporadas — você pode preservar a fidelidade do layout enquanto desbloqueia recursos modernos da web, como atualizações de UI orientadas por estado.

Para personalização avançada, certifique-se de verificar a documentação.

Veja também