要求按A4纸大小生成pdf,支持分页且内容不被截断
使用html2canvas和jspdf插件实现
通过html2canvas将HTML页面转换成图片,然后再通过jspdf将图片生成为pdf文件
一、添加依赖模块
npm install html2canvas --save
npm install jspdf --save
二、创建pdf.js全局函数文件
// 创建 pdf.js
// 引入依赖
import Vue from 'vue'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
const PDF = {}
PDF.install = function (Vue, options) {
/**
* targetDom: 需要打印的dom对象
* name:pdf的名字
* callback: 回调函数
*/
Vue.prototype.$createPdf = function (targetDom, name, callback) {
let cloneDom = targetDom.cloneNode(true)
cloneDom.style.width = targetDom.scrollWidth + 'px'
cloneDom.style.height = targetDom.scrollHeight + 'px'
cloneDom.style.background = '#FFFFFF'
document.body.appendChild(cloneDom)
html2canvas(copyDom, {
scale: 1, // 提升画面质量,但是会增加文件大小
useCORS: true, // 允许跨域图片 当图片是链接地址时,需加该属性,否组无法显示图片
imageTimeout: 0, // 图片加载延迟,默认延迟为0,单位毫秒
height: targetDom.scrollHeight, // canvas的高度设定
width: targetDom.scrollWidth, // canvas的宽度设定
dpi: window.devicePixelRatio * scale, // 将分辨率提高到特定的DPI
}).then(canvas => {
document.body.removeChild(cloneDom)
// a4纸的尺寸[592.28,841.89]
const A4_WIDTH = 592.28
const A