Search code examples
reactjshtml2canvas

Export html area as image with html2canvas


I am having a React app. I need to be able to export component as a png/jpg. I am trying to do that with html2canvas library.

I tried with this naive approach

const printDocument = () => {
  html2canvas(document.querySelector("#capture")).then(canvas => {
    document.body.appendChild(canvas);
  });
};

export default function App() {
  return (
    <div className="App">
      <div id="capture" style={{ padding: 10, background: "#f5da55" }}>
        <h4 style={{ color: "#000" }}>Hello world!</h4>
      </div>

      <button onClick={printDocument}>Print</button>
    </div>
  );
}

But I am getting an error:

TypeError
(0 , _html2canvas.html2canvas) is not a function
printDocument
/src/App.js:12:14
   9 | // };
  10 | 
  11 | const printDocument = () => {
> 12 |   html2canvas(document.querySelector("#capture")).then(canvas => {
     |              ^
  13 |     document.body.appendChild(canvas);
  14 |   });
  15 | };

How can I achieve this in ReactJs?


Solution

  • Use the following import statement

    import html2canvas from 'html2canvas';
    

    You can use useRef hook of react

    const printDocument = (domElement) => {
      html2canvas(domElement).then(canvas => {
        document.body.appendChild(canvas);
      });
    };
    
    export default function App() {
    
       const canvasRef = useRef()
    
      return (
        <div className="App">
          <div ref={canvasRef} style={{ padding: 10, background: "#f5da55" }}>
            <h4 style={{ color: "#000" }}>Hello world!</h4>
          </div>
    
          <button onClick={()=>printDocument(canvasRef.current)}>Print</button>
        </div>
      );
    }