import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const ratio = 1; //放大 兼容低分辨率屏幕清晰度

export const margin = 10; //边距
// A4宽高
export const a4Width = 595.28;
export const a4Height = 841.89;
// let pdf = null;
export const downloadPDF = (pages, splitPos, fileName = '工单') => {
  // direction : 方向

  html2canvas(pages, { scale: ratio }).then((canvas) => {
    let pdf = new jsPDF('', 'pt', 'a4');

    var imgWidth = a4Width - margin * 2;

    //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
    const ctx = canvas.getContext('2d');
    splitPos.reduce((pre, pos) => {
      const pageData = ctx.getImageData(
        0,
        pre * ratio,
        canvas.width,
        pos * ratio - pre * ratio
      );

      //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      var imgHeight = (imgWidth / canvas.width) * (pos * ratio - pre * ratio);

      pdf.addImage(pageData, 'JPEG', margin, 10, imgWidth, imgHeight);

      if (pos < canvas.height) {
        pdf.addPage();
      }
      return pos;
    }, 0);

    pdf.save(`${fileName}.pdf`);
    const blob = pdf.output('blob');
    var blob_url = URL.createObjectURL(blob);
    window.open(blob_url);
    pdf = null;
  });
};
