天天看點

使用 vue-pdf 以及Lodop實作pdf列印預覽功能

1.首先下載下傳vue-pdf : npm install vue-pdf --dev

踩坑: 頁面第一次渲染沒有問題,但是二次打開PDF的時候會遇到PDF空白的問題,控制台提示:Error during font loading: Failed to execute ‘postMessage’ on ‘Worker’: ArrayBuffer at index 0 is already detached

翻找半天發現是因為緩存問題,然後找到了一個大佬的部落格, 二次封裝的這個包

附上位址:https://blog.csdn.net/chenzhiyong12/article/details/109410200

//替換vue-pdf

npm install --save vue-pdf-signature

template部分

<el-button class="filter-item" type="primary" @click="printingShopee">測試報表列印</el-button>

    <pdf :src="testSrc"/>
           

script部分:

import pdf from 'vue-pdf-signature'
// 解決部分文字不顯示的問題
import CMapReaderFactory from 'vue-pdf-signature/src/CMapReaderFactory.js'
data() {
    return {
         testSrc: '',
      }
   }
components: {
    pdf
  },
  methods: {
  printingShopee() {
      // testSrc
      const data = {
        "param":{
          "patientName":"蒲靜111",
          "diagnoseId":"0004944952",
          "recipeName":"hhhhhhh",
          "queueName":"哈哈哈",
          "lateSignDate":"okkkkk",
          "filmingNo":"13123",
          "sex":"111",
          "sns":"'287015638468063232','287015672471285760','288526367125860352'"
        },
        "reportCode":"1619747236132"
      }
      // download 請求後端接口
      download(data).then(res => {
        console.log(res)
        if(res.code === 200) {
        //  res.result 為base64位的碼
          let datas = 'data:application/pdf;base64,' + res.result
          this.testSrc = pdf.createLoadingTask({ url: datas, CMapReaderFactory });
          console.log(this.testSrc)
          setTimeout(() => {
          // 通過調試檢查發現pdf預覽的頁面是canvas繪成的
            var printContent = document.getElementsByTagName('canvas')[0];
            console.log(printContent)
            var dataUrl = printContent.toDataURL(); // 轉成base64
            console.log(printContent)
            console.log(dataUrl)
            LODOP.PRINT_INIT("測試PDF列印功能");
            LODOP.SET_PRINT_PAGESIZE(3, 780, 100, '')
            // LODOP.ADD_PRINT_IMAGE("0mm","0mm","RightMargin:0mm","BottomMargin:0mm",dataUrl);
            LODOP.ADD_PRINT_IMAGE(0, 0, '100%', '100%', dataUrl)
            LODOP.SET_PRINT_STYLEA(0,"Stretch",2);//(不可變形)擴充縮放模式
            // LODOP.SET_PRINTER_INDEX(LODOP.GET_PRINTER_NAME(-1))
            // LODOP.PRINT()
            LODOP.PREVIEW(); //預覽列印
          },2000)
        }
      })
    },
}
           

但是我們業務要求不預覽 直接列印,

但是canvas, 必要設定width,height屬性, 或不能将display設為none, 否則列印的canvas對象就是一個空對象,那它傳回的 toDataURL()就為空 data:

是以這個很緻命 目前隻能給最外層的父元素設定了寬和高 将 pdf元件放到頁面内容外