//文件名随便取一个如:htmlToPdf.js
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import store from '../store'
export default {
  install (Vue, options) {
    Vue.prototype.getPdf = function (title) {
      var element = document.querySelector('#' + title); // 这个dom元素是要导出pdf的div容器
      setTimeout(() => {
        html2Canvas(element, {
          allowTaint: true,
          taintTest: false,
          useCORS: true,
          async: true,
          scale: '1', // 放大倍数
          dpi: '192', // 精度
        }).then(function (canvas) {
          //未生成pdf的html页面高度
          var leftHeight = canvas.height;
          var a4Width = 595.28
          var a4Height = 841.89
          //一页pdf显示html页面生成的canvas高度;
          var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);
          //pdf页面偏移
          var position = 0;
          var pageData = canvas.toDataURL('image/jpeg', 1.0);
          var pdf = new JsPDF('x', 'pt', 'a4');
          var index = 0,
            canvas1 = document.createElement('canvas'),
            height;
          pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');
          // $('.head-content').append($(
          //     '<div class="pdfTip">' +
          //     '   <div>正在生成第<span class="pdfProgress">1</span>页,共<span class="pdfTotal"></span>页...' +
          //     '</div>'));
          function createImpl (canvas) {
            if (leftHeight > 0) {
              index++;
              var checkCount = 0;
              if (leftHeight > a4HeightRef) {
                var i = position + a4HeightRef;
                for (i = position + a4HeightRef; i >= position; i--) {
                  var isWrite = true
                  for (var j = 0; j < canvas.width; j++) {
                    var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data
                    if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                      isWrite = false
                      break
                    }
                  }
                  if (isWrite) {
                    checkCount++
                    if (checkCount >= 10) {
                      break
                    }
                  } else {
                    checkCount = 0
                  }
                }
                height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                if (height <= 0) {
                  height = a4HeightRef;
                }
              } else {
                height = leftHeight;
              }
              canvas1.width = canvas.width;
              canvas1.height = height;
              // console.log(index, 'height:', height, 'pos', position);
              var ctx = canvas1.getContext('2d');
              ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);
              var pageHeight = Math.round(a4Width / canvas.width * height);
              // pdf.setPageSize(null, pageHeight)
              if (position != 0) {
                pdf.addPage();
              }
              pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, a4Width, a4Width / canvas1.width * height);
              leftHeight -= height;
              position += height;
              // $('.pdfProgress').text(index + 1);
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              if (leftHeight > 0) {
                setTimeout(createImpl, 500, canvas);
              } else {
                store.commit('setdisplayshow', true)
                document.getElementById("iframe123").src = pdf.output('datauristring');
                //   pdf.save(pdfName + '.pdf');
                // var blob = pdf.output("blob")
                // let formData = new FormData();
                // formData.append("dir", 'sz');
                // formData.append("ori", 1);
                // formData.append("origName", Date.parse(new Date()) + '.pdf');
                // formData.append("Filedata", blob);
                // Vue.prototype.$post('v1/rest/file/uploadOSS', formData, {
                //   succeedHandler: res => {
                //     window.open(res.data.path, '_blank')
                //     // var link = document.createElement('a')
                //     // link.download = Date.parse(new Date()) + '.pdf'
                //     // link.style.display = 'none';
                //     // link.href = res.data.path
                //     // document.body.appendChild(link);
                //     // link.click();
                //     // document.body.removeChild(link);                                                
                //     Toast.clear()
                //   }
                // })
                // // $('.pdfTip').remove();
              }
            }
          }
          //当内容未超过pdf一页显示的范围,无需分页
          if (leftHeight < a4HeightRef) {
            pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
            //   pdf.save(pdfName + '.pdf')
            // var blob = pdf.output("blob")
            // let formData = new FormData();
            // formData.append("dir", 'sz');
            // formData.append("ori", 1);
            // formData.append("origName", Date.parse(new Date()) + '.pdf');
            // formData.append("Filedata", blob);
            // Vue.prototype.$post('v1/rest/file/uploadOSS', formData, {
            //   succeedHandler: res => {
            //     window.open(res.data.path, '_blank')
            //     // var link = document.createElement('a')
            //     // link.download = Date.parse(new Date()) + '.pdf'
            //     // link.style.display = 'none';
            //     // link.href = res.data.path
            //     // document.body.appendChild(link);
            //     // link.click();
            //     // document.body.removeChild(link);                                                
            //     Toast.clear()
            //   }
            // })
            store.commit('setdisplayshow', true)
            document.getElementById("iframe123").src = pdf.output('datauristring');
          } else {
            try {
              pdf.deletePage(0);
              // $('.pdfTip').show();
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              setTimeout(createImpl, 500, canvas);
            } catch (err) {
              console.log(err);
            }
          }
        });
      }, 0);
    }
  }
}
 
//vue页面
<el-button @click="printProduct">打印</el-button>
    <iframe id="iframe123" frameborder="0" :width='$store.state.displayshow?"100%":"0"'  :height='$store.state.displayshow?"700":"0"'></iframe>
      //打印
      printProduct(){
        let prt='print_'+this.typenum
        this.getPdf(prt)
      },

vue html转pdf并打印的更多相关文章

  1. 用SumatraPdf实现PDF静默打印

    原文:https://yutuo.net/archives/24a22d50d6001564.html 之前做一系统,有一个打印PDF文件的需求,需求如下: 能指定打印机 能两面打印 最好能静默打印 ...

  2. vue 中展示PDF内容

    vue 中展示PDF内容 不久前有个需要改的需求,以前是直接根据链接让用户下载对应pdf文件来查看,最主要是给用户查看,然而这种并不是很安全的,其他用户可以进行下载或者使用pdf链接分享给其他人,所以 ...

  3. 想请问下PDF双面打印时(打印机自动双面打印)为什么反面那页的内容是倒过来的,应该怎么设置?

    用foxit reader 打印pdf 直接设置为双面打印并且一张2页打印,发现正反面刚好倒着来的,其实说的正反面倒着是从左右翻的角度来讲的,如果上下翻会发现刚好是这个顺序的,这个是要在双面打印设置里 ...

  4. C# ITextSharp pdf 自动打印

    PDF生成后直接进入打印预览不用下载 using iTextSharp.text; using iTextSharp.text.pdf; Document pdfDoc = new Document( ...

  5. Vue之展示PDF格式的文档

    事实上有很多种在前端展示PDF格式文档的方法,小编也用过好多种,例如有<iframe>.<embed>和<object>这些标签,但是在Vue项目里,这些方法都不能 ...

  6. java PDF分页打印

    将获取的pdf文件按页拆分:参考https://q.cnblogs.com/q/99944/ pdf文件有多页,第一页需设置横向打印,其他页设置为纵向打印. PDDocument document = ...

  7. 微信小程序 PDF下载打印

    在开发微信小程序时,需要打印生成的PDF,实现思路是:后端生成相应的PDF,微信小程序下载并打开. 但是微信小程序并不可以打印,所以需要借助其他APP比如:WPS,但是发现微信小程序down的PDF在 ...

  8. Qt编写数据导出到Excel及Pdf和打印数据

    一.前言 用Qt开发已经九年了,期间用Qt做过不少的项目,在各种项目中有个功能很常用,尤其是涉及到数据记录存储的项目,那就是需要对查询的数据进行导出到Excel,或者导出到Pdf文件,或者直接打印查询 ...

  9. springboot pdf模板打印

    1.下载Adobe Acrobat DC工具来制作pdf的模板 打开一个pdf 2.制作pdf模板 把自动生成的文本框删除 然后 拖入文本框并自定义键 导入maven 依赖 <dependenc ...

  10. vue 打开新窗口进行打印

    父文件 let { href } = this.$router.resolve({ path: ' 自己配置本地路由,不需要动态路由 ', query: 个人建议传一整个对象 }) window.op ...

随机推荐

  1. JavaScript 中的一些奇怪问题

    JavaScript 中的一些奇怪问题 JavaScript 在开发过程中可能会出现很多奇怪的问题,以下是一些示例: 1.变量提升问题: 变量提升是 JavaScript 中一个常见的问题,特别是当没 ...

  2. 524. 通过删除字母匹配到字典里最长单词 (Medium)

    问题描述 524. 通过删除字母匹配到字典里最长单词 (Medium) 给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过 ...

  3. xlwings rest api

    https://pbihub.cn/blog/964/created_at https://docs.xlwings.org/zh_CN/latest/rest_api.html xlwings &g ...

  4. Matplotlib 绘图线

    绘图过程如果我们自定义线的样式,包括线的类型.颜色和大小等. 线的类型 线的类型可以使用 linestyle 参数来定义,简写为 ls. 类型 简写 说明 'solid' (默认) '-' 实线 'd ...

  5. 类型提示和python函数中'->'的用法

    一.类型提示 在python中,我们定义一个有参函数,调用该函数时需要传入参数,如下所示: # 定义一个简单的函数 def get_full_name(first_name, last_name): ...

  6. VUE学习-渲染函数

    渲染函数 x-template 引入外面组件文件写法 <template> <h1 v-if="level === 1"> <slot>< ...

  7. 【SQL SERVER】DATEDIFF() :两个日期的日期差

    定义用法 DATEDIFF() 函数返回两个日期之间的日期差. 语法 DATEDIFF(datepart,startdate,enddate) startdate 和 enddate 参数是合法的日期 ...

  8. linux中安装doker

    1.更新yum为最新的 yum -y update 2.卸载旧版的docker sudo yum remove -y docker* 3.安装需要的软件包 yum install -y yum-uti ...

  9. TCAM and CAM memory usage inside networking devices(转)

    TCAM and CAM memory usage inside networking devices Valter Popeskic Equipment and tools, Physical la ...

  10. Amd,Cmd, Commonjs, ES6 import/export的异同点

    Amd,Cmd, Commonjs, ES6 import/export等均是模块化方案 1.Commonjs使用在Nodejs上,加载模块是同步的. 2.Amd是requirejs在推广过程中对模块 ...