首页 > 其他分享 >前端打印dom

前端打印dom

时间:2022-09-22 14:26:25浏览次数:54  
标签:function inputs dom 前端 打印 print var document

方法一

      const printWindow = window.open()
      printWindow.document.write(document.querySelector('#printBox').innerHTML)
      printWindow.print()
      printWindow.close()

方法二

print.js

// 打印类属性、方法定义
/* 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.dom = document.querySelector(dom)
  } else {
    this.isDOM(dom)
    this.dom = this.isDOM(dom) ? dom : dom.$el
  }

  this.init()
}
Print.prototype = {
  init: function() {
    var content = this.getStyle() + this.getHtml()
    this.writeIframe(content)
  },
  extend: function(obj, obj2) {
    for (var k in obj2) {
      obj[k] = obj2[k]
    }
    return obj
  },

  getStyle: function() {
    var str = '',
      styles = document.querySelectorAll('style,link')
    for (var i = 0; i < styles.length; i++) {
      str += styles[i].outerHTML
    }
    str += '<style>' + (this.options.noPrint ? this.options.noPrint : '.no-print') + '{display:none;}</style>'

    return str
  },

  getHtml: function() {
    var inputs = document.querySelectorAll('input')
    var textareas = document.querySelectorAll('textarea')
    var selects = document.querySelectorAll('select')

    for (var k = 0; k < inputs.length; k++) {
      if (inputs[k].type == 'checkbox' || inputs[k].type == 'radio') {
        if (inputs[k].checked == true) {
          inputs[k].setAttribute('checked', 'checked')
        } else {
          inputs[k].removeAttribute('checked')
        }
      } else if (inputs[k].type == 'text') {
        inputs[k].setAttribute('value', inputs[k].value)
      } else {
        inputs[k].setAttribute('value', inputs[k].value)
      }
    }

    for (var k2 = 0; k2 < textareas.length; k2++) {
      if (textareas[k2].type == 'textarea') {
        textareas[k2].innerHTML = textareas[k2].value
      }
    }

    for (var k3 = 0; k3 < selects.length; k3++) {
      if (selects[k3].type == 'select-one') {
        var child = selects[k3].children
        for (var i in child) {
          if (child[i].tagName == 'OPTION') {
            if (child[i].selected == true) {
              child[i].setAttribute('selected', 'selected')
            } else {
              child[i].removeAttribute('selected')
            }
          }
        }
      }
    }

    return this.dom.outerHTML
  },

  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.js注册插件

// 注册打印插件
import print from '@/plugin/print/print.js'
Vue.use(print)

在页面中使用

const dom = document.querySelector('#printBox')
this.$print(dom)

标签:function,inputs,dom,前端,打印,print,var,document
From: https://www.cnblogs.com/whh666/p/16719062.html

相关文章

  • 前端预览pdf文件流
    awaitapi(html).then(res=>{constblob=newBlob([res],{type:'application/pdf;charset-UTF-8'})consturl=URL.createObjectURL(blob)......
  • 前端开发人员完整路线图 2022
    前端开发人员完整路线图2022FrontendDeveloperCompleteRoadmap2022什么是前端开发人员?前端开发人员是从头开始开发和构建网站设计或在网站中实现新功能的开发人员......
  • springboot前端多传参数报错、前端多传json字段报错
    Springboot多传参数导致JSONparseerror:Unrecognizedfiled...异常   默认情况下@RequestBody标注的对象必须包含前台传来的所有字段。如果没有包含前台传来的......
  • Spring Boot 前端美化
    链接cssHtml<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"><!--href是前端的引用,后端会不显示,为了方便......
  • 前端_项目搭建
    axios利用map函数,阻止重复请求constrequestMap=newMap();axios.interceptors.request.use(config=>{//请求前if(requestMap.has(config.url)){//阻止......
  • 【Mac向】前端的一些技巧
    1删除nodejs以及npmsudorm-rf/usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}2卸载用homebrew安装的nodebrewuninstall......
  • 前端面试总结04-作用域与闭包
    作用域:全局作用域函数作用域块级作用域(es6新增)自由变量:1.一个变量在当前作用域没有定义,但被使用了2.向上级作用域,一层一层依次寻找,直到找到为止3.如果到全局作用域......
  • 【前端必会】让ESLint与Prettier一起玩耍
    背景上回说到ESlint和Prettier可能会有规则上的冲突,解决的办法有多种,好比不用Prettier不用Prettier也是一种选择配置相同的规则我们选择一种可以共存的方式可以参考......
  • media配置及把用户头像从数据库展示到前端
    写在前面其实media配置也可以完全用static代替(看你自己的选择),static代替的方法是直接在mobles.py里设置用户上传头像的时候,修改一下用户上传头像时的保存位置当设置成st......
  • 【前端】HTML编码效提升:快速生成HTML标签
    目录1.生成多级标签2.生成同级标签3.生成注释4.生成多个相同标签5.生成带class标签6生成带id标签.7.生成带内容标签18.生成带内容标签29.生成带属性标签GIF演示:快速生成HT......