html2canvas配合printjs将页面打印出pdf

import html2canvas from 'html2canvas'
import PrintJS from 'print-js'

// 打印类属性、方法定义 给需要打印的加上class.flow-print
/* eslint-disable */
const Print = function (dom, options = {}) {
  if(!dom) {
    dom = '.flow-print'
  }
  if ((typeof dom) === "string") {
    this.cloneDom = document.querySelector(dom);
  } else {
    this.isDOM(dom)
    this.cloneDom = this.isDOM(dom) ? dom : dom.$el;
  }
  this.cloneDom
  //主要修改:将打印的dom转换成图片
  html2canvas(this.cloneDom, {
    scale: 2,
    backgroundColor: null,
    width: this.cloneDom.offsetWidth,
    height: this.cloneDom.offsetHeight,
  }).then(canvas => {
      this.imgmap = canvas.toDataURL("image/png");     
  const style = '@media print { @page {size: auto; margin: 0; } body{margin:0 5px}}' ; //去除页眉页脚,size设置打印尺寸
      PrintJS({
        printable: this.imgmap,
        width: this.cloneDom.offsetWidth,
        height: this.cloneDom.offsetHeight,
        type: "image",
        maxWidth: 200,
        style: style, //去除页眉页脚
        ...options
      })
  })
};
const MyPlugin = {}
MyPlugin.install = function (Vue, options) {
  // 4. 添加实例方法
  Vue.prototype.$print = Print
}
export default MyPlugin

import Print from '@/plugins/print'
Vue.use(Print) // 注册打印
 
通过this.$print()打印
posted @   吃饭七分饱  阅读(835)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示