编程知识 cdmana.com

Using html2canvas and jspdf in Vue to generate and Download HTML pdf

1.utils New inside htmlToPdf.js

import html2canvas from "html2canvas"
import JsPDF from "jspdf"

/**
 * @param ele To generate  PDF Of DOM Elements ( Containers )
 * @param padfName PDF File name after file generation 
*/

export default {
  install(Vue, options) {
    Vue.prototype.getPdfFromHtml = function (ele, pdfFileName) {
      let eleW = ele.offsetWidth//  Get the width of the container 
      //   let eleH = ele.offsetHeight //  Get the height of the container 
      let eleH = ele.scrollHeight//  Get the height of the container 
      let eleOffsetTop = ele.offsetTop//  Get the distance from the container to the top of the document 
      let eleOffsetLeft = ele.offsetLeft//  Get the leftmost distance from the container to the document 
      var canvas = document.createElement("canvas")
      var abs = 0
      let win_in = document.documentElement.clientWidth || document.body.clientWidth//  Gets the width of the current visible window ( No scrollbars )
      let win_out = window.innerWidth//  Gets the width of the current window ( Include scroll bar )
      if (win_out > win_in) {
        // abs = (win_o - win_i)/2;    //  Get half the length of the scroll bar 
        abs = (win_out - win_in) / 2//  Get half the width of the scroll bar 
      }
      canvas.width = eleW * 2//  Make the canvas wide && High magnification twice 
      canvas.height = eleH * 2
      var context = canvas.getContext("2d")
      context.scale(2, 2) //  Enhance picture clarity 
      context.translate(-eleOffsetLeft - abs, -eleOffsetTop)
      html2canvas(ele, {
        dpi: 300,
        useCORS: true// allow canvas The canvas can request external link images across domains ,  Allow cross domain requests .
      }).then(canvas => {
        var contentWidth = canvas.width
        var contentHeight = canvas.height
        // One page pdf Show html Page generated canvas Height ;
        var pageHeight = (contentWidth / 592.28) * 841.89 //  The purpose of this writing is to keep the ratio of width to height consistent  pageHeight/canvas.width = a4 Paper height /a4 The width of the paper //  Width and canvas.width bring into correspondence with 
        // Not generated pdf Of html Page height 
        var leftHeight = contentHeight
        // Page migration 
        var position = 0
        //a4 The size of the paper [595.28,841.89], Unit pixel ,html Page generated canvas stay pdf The width and height of the picture in 
        var imgWidth = 595.28
        var imgHeight = (595.28 / contentWidth) * contentHeight
        var pageData = canvas.toDataURL("image/jpeg", 1.0)
        var pdf = new JsPDF("", "pt", "a4")
        // There are two heights to distinguish , One is html The actual height of the page , And generation pdf Page height of (841.89)
        // When the content does not exceed pdf The range of one page display , No need to paginate 
        if (leftHeight < pageHeight) {
          // stay pdf.addImage(pageData, 'JPEG',  Left , On , Width , Height ) Set in the pdf It shows that ;
          pdf.addImage(pageData, "JPEG", 5, 0, imgWidth, imgHeight)
          // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight);
        } else {
          //  Pagination 
          while (leftHeight > 0) {
            pdf.addImage(pageData, "JPEG", 5, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            // Avoid adding blank pages 
            if (leftHeight > 0) {
              pdf.addPage()
            }
          }
        }
        pdf.save(pdfFileName + ".pdf")
      })
    }
  }
}

2. stay main.js introduce

import htmlToPdf from "../src/utils/htmlToPdf"
Vue.use(htmlToPdf)

 

3. Click the button to call print Method

<!--
 * @Descriptions: 
 * @Version: 
 * @Author: 
 * @Date: 2020-12-24 17:35:44
 * @LastEditors: dongwenjie
 * @LastEditTime: 2020-12-25 09:56:46
-->
<template>
  <div id="htmltopdf">
    <img
      src="../../../public/static/img/back.jpg"
      alt=""
      width="400px"
      height="400px"
      crossOrigin="anonymous"
    />
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label=" The name of the event ">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label=" Activity area ">
        <el-select v-model="form.region" placeholder=" Please select the activity area ">
          <el-option label=" Zone one " value="shanghai"></el-option>
          <el-option label=" Area two " value="beijing"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label=" Activity time ">
        <el-col :span="11">
          <el-date-picker
            type="date"
            placeholder=" Select date "
            v-model="form.date1"
            style="width: 100%"
          ></el-date-picker>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-time-picker
            placeholder=" Selection time "
            v-model="form.date2"
            style="width: 100%"
          ></el-time-picker>
        </el-col>
      </el-form-item>
      <el-form-item label=" Instant delivery ">
        <el-switch v-model="form.delivery"></el-switch>
      </el-form-item>
      <el-form-item label=" The nature of the activity ">
        <el-checkbox-group v-model="form.type">
          <el-checkbox label=" food / Restaurant online activities " name="type"></el-checkbox>
          <el-checkbox label=" Earth pushing activity " name="type"></el-checkbox>
          <el-checkbox label=" Offline theme activities " name="type"></el-checkbox>
          <el-checkbox label=" Pure brand exposure " name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label=" Special resources ">
        <el-radio-group v-model="form.resource">
          <el-radio label=" Online brands sponsor "></el-radio>
          <el-radio label=" Offline venues are free "></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label=" Form of activity ">
        <el-input type="textarea" v-model="form.desc"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="print"> Generate pdf</el-button>
  </div>
</template>

<script>
export default {
  name: "htmltopdf",
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    print() {
      this.getPdfFromHtml(document.getElementById("htmltopdf"), "pdf");
    },
    onSubmit() {
      console.log("submit!");
    },
  },
};
</script>
<style lang="scss" scoped>
</style>

 

4. The export is shown in the figure

版权声明
本文为[Life's in danger]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225100106163c.html

Scroll to Top