//文件名随便取一个如: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. cximage函数总结(拷贝)

    链接:   https://blog.csdn.net/flame_007/article/details/89293140 http://t.zoukankan.com/lidabo-p-69233 ...

  2. REDIS基础要点

    简述:redis 单实例,单进程,当线程处理用户请求数据,基于内存对数据处理.Redis默认分为0-16号库,每个库互相隔离(数据不共享) 基础复习: 1,系统中的每个进程对应有一个fd,通过网卡连接 ...

  3. Ubuntu离线安装 MySQL 5.7

    来源:https://www.ngui.cc/article/show-581968.html?action=onClick 一.所需环境 操作系统:Ubuntu 20.04数据库:MySQL 5.7 ...

  4. Java面向对象之封装详解

    封装详解 封装 该露的露,该藏的藏 1.我们程序设计要追求"高内聚.低耦合".高内聚:类的内部数据操作细节自己完成,不允许外部干涉:低耦合:仅暴露少量的方法给外部使用. 封装(数据 ...

  5. spring boot创建多线程定时任务

    @Component@EnableScheduling // 1.开启定时任务@EnableAsync // 2.开启多线程public class MultithreadScheduleTask { ...

  6. 088_BatchApex_Callout

    global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts { publi ...

  7. python批量将png图片转换为jpg图片

    参考引用链接如下:https://www.freesion.com/article/1866518882

  8. 关于 MySQL 的 General Log 功能

    检查 General Log 输出目标 SHOW GLOBAL VARIABLES LIKE 'log_output'; # Type: Set # Default Value: FILE # Val ...

  9. Vue中的样式作用域

    介绍对于Vue样式作用域的介绍 对于所有组件中的Css都是通用的 在未指定作用域之前 在A组件中定义的 {.h1{color:red}} 同样会在b组件中生效 如果在B组件中也定义了 h1元素. 虽然 ...

  10. GPS授时仪(网络校时服务器)成功投运攀枝花市中西医结合医院

    GPS授时仪(网络校时服务器)成功投运攀枝花市中西医结合医院 技术交流:岳峰 15901092122 论述当下网络时间同步的重要性 北京华人开创公司 技术交流15901092122 概述:电脑时间走时 ...