Html 画布裁剪 svg

HtmlToCanvas crops svg

努力实现已完成的目标here。唯一的问题是我下载的 pdf 图像被右侧粗暴地裁剪了:

我深入研究并发现了 html2canvas 方法导致的问题不是 jspdf,

那么我如何使用 html2canvas 强制将 svg 正确地更改为 png

组件:

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" />
    </>
  );
}

打印按钮:

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:
    
  */}
    <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;

任何时候你正在使用 React 并且你需要使用直接操纵 dom 的库来查看使用 refs...(它有点像 react 等同于document.getElementById) - 它为您提供了对 dom 节点的引用...您可以这样做:

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>
  );
}

现场演示:https://stackblitz.com/edit/react-w5qb9a?file=src%2FApp.js

关于参考的更多信息:https://reactjs.org/docs/refs-and-the-dom.html