// 这个导出一张pdf，不会有分页中间断开的问题。但是文件比较大
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { domShowFu } from "./domShow";

export const downloadPDF = (element: HTMLDivElement, pdfName: string) => {
  if (element) {
    domShowFu("#AsyncSpinLoding", true);

    let width = element.offsetWidth / 4;
    let height = element.offsetHeight / 4;
    let limit = 14400;
    if (height > limit) {
      let contentScale = limit / height;
      height = limit;
      width *= contentScale;
    }
    html2canvas(element, {
      scale: 1,
      useCORS: true,
      backgroundColor: "#FFFFFF",
      allowTaint: false,
      ignoreElements: (element: { id: string }) => {
        if (element.id === "ignoreBtnElement") return true;
        return false;
      },
    }).then((canvas) => {
      let context: any = canvas.getContext("2d");
      let orientation;
      if (context) {
        context.mozImageSmoothingEnabled = false;
        context.webkitImageSmoothingEnabled = false;
        context.msImageSmoothingEnabled = false;
        context.imageSmoothingEnabled = false;
      }
      let pageData = canvas.toDataURL("image/jpg", 1.0);
      let img = new Image();
      img.src = pageData;
      img.onload = function () {
        img.width /= 2;
        img.height /= 2;
        img.style.transform = "scale(0.5)";
        let pdf;
        orientation = width > height ? "l" : "p";
        pdf = new jsPDF(orientation as "l", "mm", [width, height]);
        pdf.addImage(pageData, "jpeg", 0, 0, width, height);
        pdf.save(pdfName + ".pdf");

        domShowFu("#AsyncSpinLoding", false);
      };
    });
  }
};

