1. 程式人生 > >vue-列印當前頁面為pdf檔案(不分頁----一頁)

vue-列印當前頁面為pdf檔案(不分頁----一頁)

1、npm 安裝
npm install jspdf --save
npm install --save html2canvas
2、在需要列印的頁面匯入
import html2Canvas from “html2canvas”;
import JsPDF from “jspdf”;
3、頁面直接呼叫該方法即可
printOut() {
var title = this.teacherName;
var that = this;
var shareContent = document.querySelector("#subOutputRank"); //需要截圖的包裹的(原生的)DOM 物件
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(document.querySelector("#subOutputRank"), {
allowTaint: 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/jpeg", 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");
      that.dianpingShow = true;
    };
  });
}