如何在nextjs 13中将div的内容下载为JPEG文件?

ss2ws0br  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在设计一个名片生成器,但不知道如何下载卡片。它只是一个简单的div。
有没有办法把这个div下载成JPEG格式?

tyky79it

tyky79it1#

我不久前就这么做了,你可以使用“html2canvas”npm包。它工作得非常快。这就是你如何将div的html内容下载成图像JPEG格式。
如果你需要更多的帮助和一个小例子,你可以参考这个简单的指南:Convert Div to Image and download

import React, { useRef, useState } from "react";
import html2canvas from "html2canvas";

const DivToImage = () => {
  const exportDivImageRef: any = useRef();
  const [downloading, setDownloading] = useState<boolean>(false);

  const exportAsImage = async (element, imageFileName) => {
    setDownloading(true);
    try {
      const html: any = document.getElementsByTagName("html")[0];
      const body: any = document.getElementsByTagName("body")[0];
      let htmlWidth = html.clientWidth;
      let bodyWidth = body.clientWidth;
      const newWidth = element.scrollWidth - element.clientWidth;
      if (newWidth > element.clientWidth) {
        htmlWidth += newWidth;
        bodyWidth += newWidth;
      }
      html.style.width = htmlWidth + "px";
      body.style.width = bodyWidth + "px";
      const canvas = await html2canvas(element, {
        allowTaint: true,
        useCORS: true,
      });
      const image = canvas.toDataURL("image/png", 1.0);
      downloadImage(image, imageFileName);
      html.style.width = null;
      body.style.width = null;
    } catch (error) {
      setDownloading(false);
    }
  };

  const downloadImage = (blob, fileName) => {
    try {
      const fakeLink: any = window.document.createElement("a");
      fakeLink.style = "display:none;";
      fakeLink.download = fileName;

      fakeLink.href = blob;

      document.body.appendChild(fakeLink);
      fakeLink.click();
      document.body.removeChild(fakeLink);

      fakeLink.remove();
      setDownloading(false);
      setDownloading(false);
    } catch (error) {
      setDownloading(false);
    }
  };

  return (
    <>
      <div ref={exportRef}>
        <h4>Hello world on Image!</h4>
      </div>
      <button onClick={downloadImage}>Download Card Image</button>
    </>
  );
};

相关问题