首页 > 其他分享 >JS 前端自适应打印

JS 前端自适应打印

时间:2022-12-09 16:33:46浏览次数:33  
标签:function obj dom 前端 打印 JS iframe print document

第一种打印:

首先是安装

npm install --save html2canvas

  

然后在 utils 包

import html2canvas from "html2canvas";

// 打印类属性、方法定义
/* eslint-disable */
const Print = function (dom, options) {
  if (!(this instanceof Print)) return new Print(dom, options);

  this.options = this.extend(
    {
      noPrint: ".no-print",
    },
    options
  );

  if (typeof dom === "string") {
    this.cloneDom = document.querySelector(dom);
  } else {
    this.isDOM(dom);
    this.cloneDom = this.isDOM(dom) ? dom : dom.$el;
  }

  //主要修改:将打印的dom转换成图片
  html2canvas(this.cloneDom).then((canvas) => {
    this.imgmap = canvas.toDataURL();
    setTimeout(() => {
      this.dom = `<div style='width:100%;height:100%;'><img style='width:100%;height:auto;' src='${this.imgmap}'/></div>`;
      this.init();
    });
  });
};
Print.prototype = {
  init: function () {
    var content = this.dom;
    this.writeIframe(content);
  },
  extend: function (obj, obj2) {
    for (var k in obj2) {
      obj[k] = obj2[k];
    }
    return obj;
  },

  writeIframe: function (content) {
    var w,
      doc,
      iframe = document.createElement("iframe"),
      f = document.body.appendChild(iframe);
    iframe.id = "myIframe";
    //iframe.style = "position:absolute;width:0;height:0;top:-10px;left:-10px;";
    iframe.setAttribute(
      "style",
      "position:absolute;width:0;height:0;top:-10px;left:-10px;"
    );
    w = f.contentWindow || f.contentDocument;
    doc = f.contentDocument || f.contentWindow.document;
    doc.open();
    doc.write(content);
    doc.close();
    var _this = this;
    iframe.onload = function () {
      _this.toPrint(w);
      setTimeout(function () {
        document.body.removeChild(iframe);
      }, 100);
    };
  },

  toPrint: function (frameWindow) {
    try {
      setTimeout(function () {
        frameWindow.focus();
        try {
          if (!frameWindow.document.execCommand("print", false, null)) {
            frameWindow.print();
          }
        } catch (e) {
          frameWindow.print();
        }
        frameWindow.close();
      }, 10);
    } catch (err) {
      console.log("err", err);
    }
  },
  isDOM:
    typeof HTMLElement === "object"
      ? function (obj) {
          return obj instanceof HTMLElement;
        }
      : function (obj) {
          return (
            obj &&
            typeof obj === "object" &&
            obj.nodeType === 1 &&
            typeof obj.nodeName === "string"
          );
        },
};
const MyPlugin = {};
MyPlugin.install = function (Vue, options) {
  // 4. 添加实例方法
  Vue.prototype.$print = Print;
};
export default MyPlugin;

  

main.ja 挂载

//打印JS文件
import Print from "@/utils/print";
Vue.use(Print); // 注册

  

应用

this.$print(document.getElementById(" 这里是要打印的内容的外层 div 的 id "));

  

第二种方法:

在调用打印方法内放置以下内容

//获取打印的页面内容
      let subOutputRankPrint = document.getElementById("print1");
      let newContent = subOutputRankPrint.innerHTML;
      let oldContent = document.body.innerHTML;
      document.body.innerHTML = newContent;
      //页面打印缩放比例设置
      document.getElementsByTagName("body")[0].style.zoom = 0.92;
      //检测是否是IE 如果是ie进行页眉页脚
      if (!!window.ActiveXObject || "ActiveXObject" in window) {
        var hkey_root, hkey_path, hkey_key;
        hkey_path =
          "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet" +
          "Explorer\\PageSetup\\";
        try {
          var RegWsh = new ActiveXObject("WScript.Shell");
          RegWsh.RegWrite(hkey_path + "header", "");
          RegWsh.RegWrite(hkey_path + "footer", "");
        } catch (e) {}
      }
      window.print();
      window.location.reload();
      //将原有页面还原到页面
      document.body.innerHTML = oldContent;
      return false;

  

加上 scss

<style lang="scss" scoped>
// chrome下进行页眉页脚消除 使用css 样式进行消除
// 测试ie11,chrome,firefox,edge 可消除页眉页脚
@media print {
  @page {
    margin: 0;
    //控制是使用a4还是使用其它纸张规格
    size: auto;
  }
}
</style>

  

 

标签:function,obj,dom,前端,打印,JS,iframe,print,document
From: https://www.cnblogs.com/majiayin/p/16969296.html

相关文章

  • JS——Math(数学&随机方法)
    Math对象方法与其他全局对象不同,Math对象没有构造函数。方法和属性是静态的可以在不首先创建Math对象的情况下使用所有方法和属性(常量)方法描述abs(x)返回x......
  • JS 判断数组包含另一个数组
    ES6方法:1、findIndex (跟find类似,返回值不一样,findIndex找到则返回元素下标,否则返回-1)functiongetInclude(arr1,arr2){lettemp=[]for(constitemofa......
  • 转发:Midway Serverless 发布 2.0,一体化让前端研发再次提效
    自去年MidwayServerless1.0发布之后,许多业务开始尝试其中,并利用Serverless容器的弹性能力,减少了大量研发人员对基础设施和运维的关注。对前端开发者而言,他们只需写几......
  • 转发:前端组件化之方案探究
    背景公司目前基于多业务部门,很多业务组件和功能逻辑都具有较高的普适性,但与此同时各业务部分和开发人员缺乏一定的交流平台,更多的是在遇到对应需求时会简单内部讨论一番,......
  • 转发:前端组件化之Monorepo方案实战
    前言在上一篇的前端组件化方案探究中,我们研究了什么是组件化以及我们为什么需要组件化。也调研和测试了一些开源项目,并且在使用、学习、研究、对比之后最终确定了以 pnpm......
  • js 大文件分片上传处理
    ​ 前言文件上传是一个老生常谈的话题了,在文件相对比较小的情况下,可以直接把文件转化为字节流上传到服务器,但在文件比较大的情况下,用普通的方式进行上传,这可不是一个好......
  • 直播系统app源码,js操作在当前日期加减(天、周、月、年数)
    直播系统app源码,js操作在当前日期加减(天、周、月、年数)1.项目案例首先,我们创建个获取当前日期的变量nowDate,项目中需求是设置在当前时间的15天后做xxx事情,写一个方法 ......
  • com.alibaba.fastjson 对象转json剔除字段
    com.alibaba.fastjson对象转json剔除字段​​问题背景描述​​​​问题处理​​问题背景描述java代码保存数据到mysql的同时需要保存一份到es,由于对象字段很多,建两个实体类......
  • Spring boot 工程,http打印日志太多
    1、resources下添加配置文件:logback.xml,简单配置如下<?xmlversion="1.0"encoding="UTF-8"?><configurationscan="true"scanPeriod="60seconds"debug="false"><appe......
  • java-net-php-python-jsp汽车租赁管理系统计算机毕业设计程序
    OverridetheentrypointofanimageIntroducedinGitLabandGitLabRunner9.4.Readmoreaboutthe extendedconfigurationoptions.Beforeexplainingtheav......