Search code examples
reactjsjspdfhtml2canvas

HtmlToCanvas crops svg


Trying to achieve whats done here. Only problem my downloaded pdf has image croped brutally by right: enter image description here

I dive into and catch html2canvas method cause the issue not jspdf,

So how can I force change svg to png properly using html2canvas

component:

import PrintButton from "../../../components/print/print";

function QrcodeComponent(props) {
  return (
    <>
      <div id={"barcodeCont"}>
        <QRCode level="L" style={{ width: 256 }} value={JSON.stringify({})} />
      </div>
      <PrintButton id="barcodeCont" />
    </>
  );
}

PrintButton:

import React from "react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

const pxToMm = (px) => {
  return Math.floor(px / document.getElementById("myMm").offsetHeight);
};

const PrintButton = ({ id, label }) => (
  <div className="mt2">
    {/*
    Getting pixel height in milimeters:
    https://stackoverflow.com/questions/7650413/pixel-to-mm-equation/27111621#27111621
  */}
    <div id="myMm" style={{ height: "1mm" }} />

    <div
      onClick={() => {
        const input = document.getElementById(id);
        const inputHeightMm = pxToMm(input.offsetHeight);
        const a4WidthMm = 210;
        const a4HeightMm = 297;

        html2canvas(input).then((canvas) => {
          const imgData = canvas.toDataURL("image/png");//here: this image already cropped..
          let pdf = new jsPDF();
          // Document of a4WidthMm wide and inputHeightMm high
          if (inputHeightMm > a4HeightMm) {
            // elongated a4 (system print dialog will handle page breaks)
            pdf = new jsPDF("p", "mm", [inputHeightMm + 161, a4WidthMm]);
          } else {
            // standard a4
            pdf = new jsPDF();
          }
          pdf.addImage(imgData, "PNG", 0, 0);
          pdf.save(`${id}.pdf`);
        });
      }}
    >
      <button type="button" className="btn btn-lime">
        <i className="fa fa-download"></i> Download{" "}
      </button>
    </div>
  </div>
);

export default PrintButton;

Solution

  • Any time you're using React and you need to use libs that directly manipulate the dom look into using refs... (it's sort of the react equivalent of document.getElementById) - it gives you a reference to the dom node... You can do something like this:

    import React, { useRef } from "react";
    import html2canvas from "html2canvas";
    import { jsPDF } from "jspdf";
    import "./style.css";
    
    export default function App() {
      const captureRef = useRef(null);
    
      const getScreenshot = async () => {
        const canvas = await html2canvas(captureRef.current);
        const img = canvas.toDataURL("image/png");
        
        const doc = new jsPDF();
        doc.addImage(img, 10, 10);
        doc.save("a4.pdf");
      };
    
      return (
        <div className="wrapper">
          <div ref={captureRef} className="to-capture">
            <p>
              This enitre <code>div</code> will be captured
            </p>
          </div>
          <button onClick={getScreenshot}>Get Screenshot!</button>
        </div>
      );
    }
    

    Live demo: https://stackblitz.com/edit/react-w5qb9a?file=src%2FApp.js

    More info on refs: https://reactjs.org/docs/refs-and-the-dom.html