vue pdf下載

主要技術棧是Vue,兩個庫: html

    html2canvas npm地址npm

    jspdf canvas

 

具體實現代碼以下:iview

 

<template>
  <div class="priview_resume_container">
        <div style="font-size: 16px" @click="getResume">點這裏下載 </div>
  </div>
</template>
<script>
  export default {
    name: 'priviewResume',
    methods: {
      getResume() {
        this.commonUtils.generateResume(
          $('.priview_resume_container')[0],
          '測試'
        )
      }
    },
    components: {}
  }
</script>
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export const generateResume = (el, name) => {
  html2canvas(el).then(canvas => {
    let contentWidth = canvas.width
    let contentHeight = canvas.height
    //一頁pdf顯示html頁面生成的canvas高度;
    let pageHeight = (contentWidth / 592.28) * 841.89
    //未生成pdf的html頁面高度
    let leftHeight = contentHeight
    //頁面偏移
    let position = 0
    //a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
    let imgWidth = 595.28
    let imgHeight = (592.28 / contentWidth) * contentHeight
    let pageData = canvas.toDataURL('image/jpeg', 1.0)
    let pdf = new JsPDF('', 'pt', 'a4')
    //有兩個高度須要區分,一個是html頁面的實際高度,和生成pdf的頁面高度(841.89)
    //當內容未超過pdf一頁顯示的範圍,無需分頁
    if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    } else {
      while (leftHeight > 0) {
        //arg3-->距離左邊距;arg4-->距離上邊距;arg5-->寬度;arg6-->高度
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
        leftHeight -= pageHeight
        position -= 841.89
        //避免添加空白頁
        if (leftHeight > 0) {
          //添加新頁
          pdf.addPage()
        }
      }
    }
    pdf.save(`${name}.pdf`)
  })
}

 

歡迎關注公衆號,進一步技術交流:jsp

相關文章
相關標籤/搜索