VUE中將頁面導出爲圖片或者PDF

導出爲圖片

1.將頁面html轉換成圖片   npm install html2canvas --savehtml

2.在須要導出的頁面引入  import html2canvas from 'html2canvas';npm

3.在 methods 中添加方法  canvas

 

dataURLToBlob(dataurl) {//ie 圖片轉格式
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type: mime})
},
downloadResult(name) {
let canvasID = document.body
let a = document.createElement('a');
html2canvas(canvasID).then(canvas => {
let dom = document.body.appendChild(canvas);
dom.style.display = "none";
a.style.display = "none";
document.body.removeChild(dom);
let blob = this.dataURLToBlob(dom.toDataURL("image/png"));
a.setAttribute("href", URL.createObjectURL(blob));
a.setAttribute("download", name + ".png")
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(blob);
document.body.removeChild(a);
});
},
printOut(name) {
// 我的觀察只是截取可見範圍以及如下的區域,因此先將滾動條置頂
$(window).scrollTop(0); // jQuery 的方法
document.body.scrollTop = 0; // IE的
document.documentElement.scrollTop = 0; // 其餘
this.downloadResult(name)
},跨域

 

 

導出爲PDF

1.將頁面html轉換成圖片  npm install html2canvas --saveapp

2.將圖片生成pdf  npm install jspdf --savedom

3.在須要導出的頁面引入  import html2canvas from 'html2canvas';   import JsPDF from 'jspdf'jsp

4.在 methods 中添加方法this

printOut(name) {
let shareContent = document.body,//須要截圖的包裹的(原生的)DOM 對象
width = shareContent.clientWidth, //獲取dom 寬度
height = shareContent.clientHeight, //獲取dom 高度
canvas = document.createElement("canvas"), //建立一個canvas節點
scale = 2; //定義任意放大倍數 支持小數
canvas.width = width * scale; //定義canvas 寬度 * 縮放
canvas.height = height * scale; //定義canvas高度 *縮放
canvas.style.width = shareContent.clientWidth * scale + "px";
canvas.style.height = shareContent.clientHeight * scale + "px";
canvas.getContext("2d").scale(scale, scale); //獲取context,設置scale
let opts = {
scale: scale, // 添加的scale 參數
canvas: canvas, //自定義 canvas
logging: false, //日誌開關,便於查看html2canvas的內部執行流程
width: width, //dom 原始寬度
height: height,
useCORS: true, // 【重要】開啓跨域配置
};url

html2Canvas(shareContent, opts).then(() => {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一頁pdf顯示html頁面生成的canvas高度;
var pageHeight = (contentWidth / 592.28) * 841.89;
//未生成pdf的html頁面高度
var leftHeight = contentHeight;
//頁面偏移
var position = 0;
//a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
var imgWidth = 595.28;
var imgHeight = (592.28 / contentWidth) * contentHeight;
var pageData = canvas.toDataURL("image/jpeg", 1.0);
var PDF = new JsPDF("", "pt", "a4");
if (leftHeight < pageHeight) {
PDF.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) {
PDF.addPage();
}
}
}
PDF.save(name + ".pdf"); // 這裏是導出的文件名
});
},spa

相關文章
相關標籤/搜索