0

I made a small page for testing purposes that from an uploaded docx it extracts the HTML. I want to show the preview of the first page of the document as an Image. I already managed to create a component that does that. From the HTML it converts it to an image. The problem is that this conversion shows the image without the format of the document. How can I achieve to show just the first page with the correct format?

Component:

import React, { useState } from "react";
import mammoth from "mammoth";
import * as htmlToImage from 'html-to-image';
import process from "process/browser";
import { Buffer } from 'buffer';
window.Buffer = Buffer;



function DocxToHtmlConverter() {
  const [htmlCode, setHtmlCode] = useState("");
  const [imageUrl, setImageUrl] = useState("");

  const handleFileInputChange = async (event) => {
    const file = event.target.files[0];
    const result = await mammoth.convertToHtml({ arrayBuffer: file });
    setHtmlCode(result.value);
    console.log(result)
  };

  const handleConvertToImage = () => {
    htmlToImage.toPng(document.getElementById('html-container'))
      .then(function (dataUrl) {
        setImageUrl(dataUrl);
      })
      .catch(function (error) {
        console.error('oops, something went wrong!', error);
      });
  }

  return (
    <div>
      <h2>Convert Docx to HTML and Image</h2>
      <input type="file" onChange={handleFileInputChange} />
      <button onClick={handleConvertToImage}>Convert to Image</button>
      <div id="html-container" dangerouslySetInnerHTML={{ __html: htmlCode }} />
      {imageUrl && <img src={imageUrl} alt="Converted HTML to Image" />}
    </div>
  );
}

export default DocxToHtmlConverter;

App.js:

import React from "react";
import DocxToHtmlConverter from "./DocxToHtmlConverter";
// import DocxHtml from "./DocxHtml";
// import WordToHtmlPreview from "./DocxToImageConverter";

function App() {
  return (
    <div className="App">
      <DocxToHtmlConverter />
      {/* <DocxHtml></DocxHtml> */}
      {/* <WordToHtmlPreview/> */}
    </div>
  );
}

export default App;
rax-hacks
  • 25
  • 5
  • https://stackoverflow.com/questions/27957766/how-do-i-render-a-word-document-doc-docx-in-the-browser-using-javascript This isn't generally possible on the front end, Word has a unique rendering engine which is not supported by browsers. Looks like someone recently made a package that might help: https://www.npmjs.com/package/docx-preview – Chris B. Apr 04 '23 at 00:11
  • @ChrisB. thanks for the answer. I already tried using it, but it doesn't work as I want. Do you know if it's possible with docx-preview I can extract the HTML and render an image to maintain the format? – rax-hacks Apr 04 '23 at 16:45

0 Answers0