import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export const downloadPDF = (page, fileName = 'test', callBack) => {
    html2canvas(page,{allowTaint: true,useCORS: true,height: page.scrollHeight,windowHeight: page.scrollHeight}).then(function(canvas) {
        canvas2PDF(canvas, fileName, callBack);
    });
};
const canvas2PDF = (canvas, fileName, callBack) => {
    let contentWidth = canvas.width;
    console.log(contentWidth);
    let contentHeight = canvas.height;
    // 一页pdf显示html页面生成的canvas高度;
    let pageHeight = contentWidth / 592.28 * 841.89;
    // let pageHeight = 841.89;

    // 未生成pdf的html页面高度
    let leftHeight = contentHeight;
    // 页面偏移
    let position = 0;
    // html页面生成的canvas在pdf中图片的宽高（本例为：横向a4纸[841.89,592.28]，纵向需调换尺寸）
    let imgWidth = 550;
    let imgHeight = 592.28 / contentWidth * contentHeight;
    // let imgHeight = 841.89;

    let pageData = canvas.toDataURL('image/jpeg', 1.0);
    let PDF = new jsPDF('', 'pt', 'a4');
    // 两个高度需要区分: 一个是html页面的实际高度，和生成pdf的页面高度
    // 当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < pageHeight) {
        PDF.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight)
    } else {
        while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
            leftHeight -= pageHeight;
            position -= 841.89;
            // 避免添加空白页
            if (leftHeight > 0) {
                PDF.addPage();
            }
        }
    }
    PDF.save(fileName + '.pdf')

    callBack()






    // let contentWidth = canvas.width;
    // let contentHeight = canvas.height;
    // console.log(contentWidth,contentHeight);
    // let imgHeight = contentHeight;
    // let imgWidth = contentWidth/2;

    // // 第一个参数： l：横向  p：纵向
    // // 第二个参数：测量单位（"pt"，"mm", "cm", "m", "in" or "px"）
    // let pdf = new jsPDF('l', 'pt', 'a4');

    // pdf.addImage(
    //   canvas.toDataURL("image/jpeg", 1.0),
    //   "JPEG",
    //   0,
    //   0,
    //   imgWidth,
    //   imgHeight
    // );
    // pdf.save("导出.pdf");
};