第1个回答 2022-06-18
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
function printOut(DomName) {
console.log("正在帮您导出......")
//title,随意设置,也可以提出来做参数,传入进来,自己发挥
var title = '测试啊';
var that = this;
var shareContent = DomName; //需要截图的包裹的(原生的)DOM 对象
//打印看有没有获取到dom
console.log(shareContent)
var width = shareContent.offsetWidth; //获取dom 宽度
var height = shareContent.offsetHeight; //获取dom 高度
var canvas = document.createElement("canvas"); //创建一个canvas节点
var scale = 2; //定义任意放大倍数 支持小数
canvas.width = width * scale; //定义canvas 宽度 * 缩放,在此我是把canvas放大了2倍
canvas.height = height * scale; //定义canvas高度 *缩放
canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
html2Canvas(DomName, {
//允许跨域图片的加载
useCORS: true,
}).then(function (canvas) {
var context = canvas.getContext("2d");
// 【重要】关闭抗锯齿
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.msImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
var imgData = canvas.toDataURL('image/', 1.0); //转化成base64格式,可上网了解此格式
var img = new Image();
img.src = imgData;
img.onload = function () {
img.width = img.width / 2; //因为在上面放大了2倍,生成image之后要/2
img.height = img.height / 2;
img.style.transform = "scale(0.5)";
if (this.width > this.height) {
//此可以根据打印的大小进行自动调节
var doc = new JsPDF("l", "mm", [
this.width * 0.555,
this.height * 0.555
]);
} else {
var doc = new JsPDF("p", "mm", [
this.width * 0.555,
this.height * 0.555
]);
}
doc.addImage(
imgData,
"jpeg",
10,
0,
this.width * 0.505,
this.height * 0.545
);
doc.save(title + "-文件.pdf");
console.log("倒数3秒导出啦")
};
});
}
//导出方法
export {
printOut
}