Front-end Vue page generates PDF

0. Foreword

Recently, the project has a development requirement to export table data to generate PDF. There are two methods for this.

  • One is to directly invoke printing, and the user manually chooses to export the PDF through the printing page provided by the browser. Of course, this method has poor compatibility and bad experience, which is obviously not the effect we want.
  • First generate the report page, that is, the regular page; then convert the page into a picture (the component html2canvas used); finally export the picture to PDF (the component jspdf used).

1. Installation dependencies

npm install --save html2canvas  // 页面转图片
npm install jspdf --save  // 图片转pdf

2. Export image to PDF

Create a new index.vue page:

<template>
  <div ref="pdf">
    这是待转换的页面,点击 
    <button @click="handleExport">导出</button> 按钮,完成导出操作。
  </div>
</template>

<script>
import {
    
    downloadPDF} from "@/util/pdf.js"  //工具方法,导出操作
export default {
    
    
  name: "pdf",
  data() {
    
    
    return {
    
    };
  },
  methods: {
    
    
    handleExport(){
    
    
      downloadPDF(this.$refs.pdf)
    }
  }
};
</script>

A tool method downloadPDF() is called in the button click event, which comes from the tool class pdf.js:
because some requirements require the generated pages to be printed on A4 paper, the width and height dimensions of the pdf generation cannot be set as above. It needs to be adjusted according to the size ratio of A4 paper (other printing requirements are the same, just use the corresponding paper ratio)

import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export const downloadPDF = (page) => {
    
    
  html2canvas(page).then(function (canvas) {
    
    
    canvas2PDF(canvas)
  })
}

const canvas2PDF = (canvas) => {
    
    
  let contentWidth = canvas.width
  let contentHeight = canvas.height

  //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
  let imgWidth = 595.28
  let imgHeight = (592.28 / contentWidth) * contentHeight

  // 第一个参数: l:横向  p:纵向
  // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
  let pdf = new jsPDF('p', 'pt')

  pdf.addImage(
    canvas.toDataURL('image/jpeg', 1.0),
    'JPEG',
    0,
    0,
    imgWidth,
    imgHeight
  )

  pdf.save('导出.pdf')
}

Guess you like

Origin blog.csdn.net/DZQ1223/article/details/131514723