//html转图片打印（解决element table打印不全的问题）
import html2canvas from "html2canvas";
import printJS from "print-js";

/**
 * html转图片
 * @param printContent
 * @param callback
 */
export const html2Canvas = (printContent, callback) => {
    // 获取dom 宽度 高度
    const width = printContent.clientWidth;
    const height = printContent.clientHeight;
    // 创建一个canvas节点
    const canvas = document.createElement("canvas");
    console.log('width',width,'height', height)
    const scale = 5.5; // 定义任意放大倍数，支持小数；越大，图片清晰度越高，生成图片越慢。
    canvas.width = 6000; // 定义canvas 宽度 * 缩放
    canvas.height = height * scale; // 定义canvas高度 *缩放
    canvas.style.width = 1500 + "px";
    canvas.style.height = height * scale + "px";
    canvas.getContext("2d").scale(scale, scale); // 获取context,设置scale

    const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动轴滚动的长度
    const scrollLeft =
        document.documentElement.scrollLeft || document.body.scrollLeft; // 获取水平滚动轴的长度

    html2canvas(printContent, {
        canvas,
        backgroundColor: null,
        useCORS: true,
        windowHeight: document.body.scrollHeight,
        scrollX: -scrollLeft, // 解决水平偏移问题，防止打印的内容不全
        scrollY: -scrollTop
        //background: "#ffffff", // 一定要添加背景颜色，否则出来的图片，背景全部都是透明的
    })
        .then(canvas => {
            const url = canvas.toDataURL("image/png");
            console.log("canvas url :" + url);
            callback({ url: url });
        })
        .catch(err => {
            console.error(err);
        });
};

/**
 * 用printJs打印图片
 * @param url
 * @param callback
 */
export const printImg = (url, callback) => {
    printJS({
        printable: url,
        type: "image",
        documentTitle: "", // 标题
        style: "@page{size:auto;margin: 1cm ;}", // 去除页眉页脚
        onStart: () => {
            console.log("打印开始");
        },
        onEnd: () => {
            console.log("打印完成");
        }
    });
};

/**
 * html转图片打印
 * @param dom
 * @param callback
 */
export const html2CanvasPrint = (dom, callback) => {
    //1、html转图片
    html2Canvas(dom, canvasRes => {
        //2、打印图片
        printImg(canvasRes.url, callback);
    });
};
