前端打印之实际工具

main.js
import Prints from '@/utils/print'
Vue.use(Prints) // 注册
print.js(这里的图片地址是公司的后端返回的文件流)
// 打印类属性、方法定义
/* eslint-disable */
import Watermark  from './watermark'
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(options);
};
Print.prototype = {
  init:async function(options) {
    let content = this.getStyle() + this.getHtml();
    await this.writeIframe(content);
    let contentDom = document.getElementById("myIframe").contentWindow.document.getElementById(options);
    await  Watermark.set('水印',contentDom)
  },
  extend: function (obj, obj2) {
    for (let k in obj2) {
      obj[k] = obj2[k];
    }
    return obj;
  },

  getStyle: function () {
    let str = "",
      styles = document.querySelectorAll('style,link');
    for (let i = 0; i < styles.length; i++) {
      str += styles[i].outerHTML;
    }
    str += "<style>" + (this.options.noPrint ? this.options.noPrint : '.no-print') + "{display:none;}</style>";
    str += "<style>html,body,div{height: auto;font-size:14px}</style>";
    return str;
  },

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

    for (let 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 (let k2 = 0; k2 < textareas.length; k2++) {
      if (textareas[k2].type == 'textarea') {
        textareas[k2].innerHTML = textareas[k2].value
      }
    }

    for (let k3 = 0; k3 < selects.length; k3++) {
      if (selects[k3].type == 'select-one') {
        let child = selects[k3].children;
        for (let 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;
  },
  getwatermark:function () {
    let watermarkjs = `<script type="text/javascript" src="./watermark.js"></script>`
    return watermarkjs
  },
  writeIframe: function (content) {
    let w, doc, iframe = document.createElement('iframe'),
      f = document.body.appendChild(iframe);
    iframe.id = "myIframe";
    // 本地测试的时候看
    // iframe.setAttribute('style', 'position:absolute;width:100vw;height:100vw;top:100px;left:100px;');
    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();
    let _this = this
    iframe.onload = function(){
      _this.toPrint(w,doc);
      setTimeout(function () {
        document.body.removeChild(iframe)
      }, 100)
    }
  },
  toPrint: function (frameWindow,frameDoc) {
    try {
      setTimeout(function () {
        // let mediaQueryList = frameWindow.matchMedia('print');
        // mediaQueryList.addListener(function(mql) {
        // if (mql.matches) {
        //  console.log('frameDoc',frameDoc.documentElement.scrollHeight);
        // }
        // });
        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
watermark.js
const watermark = {}
const createLeftWatermarkStyle = (top, left, width, height) => {
  return `pointerEvents: none;top:  ${top}%;left: ${left}%;position: fixed;z-index: 100000;width: ${width}px;opacity: 0.4;height: ${height}px`
}

const createRightWatermarkStyle = (top, left, width, height) => {
  return `pointerEvents: none;top:  ${top}%;right: ${left}%;position: fixed;z-index: 100000;width: ${width}px;opacity: 0.4;height: ${height}px`
}

const createWatermark = (top, left, width, height, src, type) => {
  const img = document.createElement('img')
  if (type === 'left') {
    img.style = createLeftWatermarkStyle(top, left, width, height)
  } else {
    img.style = createRightWatermarkStyle(top, left, width, height)
  }
  img.src = src
  return img
}
/**
  * param str:显示的水印文字
  * param containerPro:需要添加水印的容器DOM对象
  */
const setWatermark = (str, containerPro) => {
  let row
  const width = 103
  const height = 103
  const scrollHeight = containerPro.scrollHeight
  const col = Math.floor(containerPro.scrollWidth / 4)
  if (containerPro.id === 'processCont') {
    row = 3
  } else {
    row = 3
    for (let i = 1; i < row; i++) {
      // const top = (i * (height + 360) + (i - 1) * (height + 360)) / scrollHeight * 100
      const top = ((2 * i - 1) * (height + 360)) / scrollHeight * 100
      const imgBox = createWatermark(top, col, width, height, '/api/storageFile/fdfs/downloadFile?fileName=d9c0ff0b932eddde0a48840f22d69219.jpeg&filePath=group1/M00/00/87/cvHE5mRd492AOJ16AADjGYQNxvI25.jpeg', 'left')
      containerPro.appendChild(imgBox)

      const imgBox2 = createWatermark(top, col, width, height, '/api/storageFile/fdfs/downloadFile?fileName=d9c0ff0b932eddde0a48840f22d69219.jpeg&filePath=group1/M00/00/87/cvHE5mRd492AOJ16AADjGYQNxvI25.jpeg')
      containerPro.appendChild(imgBox2)
    }
  }
  for (let i = 1; i < row; i++) {
    // const top = (i * (height + 360) + (i - 1) * (height + 360)) / scrollHeight * 100
    const top = ((2 * i - 1) * (height + 360)) / scrollHeight * 100
    const imgBox = createWatermark(top, col, width, height, '/api/storageFile/fdfs/downloadFile?fileName=d9c0ff0b932eddde0a48840f22d69219.jpeg&filePath=group1/M00/00/87/cvHE5mRd492AOJ16AADjGYQNxvI25.jpeg', 'left')
    containerPro.appendChild(imgBox)
    const imgBox2 = createWatermark(top, col, width, height, '/api/storageFile/fdfs/downloadFile?fileName=d9c0ff0b932eddde0a48840f22d69219.jpeg&filePath=group1/M00/00/87/cvHE5mRd492AOJ16AADjGYQNxvI25.jpeg')
    containerPro.appendChild(imgBox2)
  }
}
// 该方法只允许调用一次
watermark.set = function(str, containerPro) {
  setWatermark(str, containerPro)
}
export default watermark

[非常感谢https://github.com/junhunlrw/waterproject 及在博客木子李大哥的支持](https://github.com/junhunlrw/waterproject "非常感谢https://github.com/junhunlrw/waterproject 及在博客木子李大哥的支持") 如需改进,请大家畅所欲言
posted @   jialiangzai  阅读(10)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异

喜欢请打赏

扫描二维码打赏

微信打赏

点击右上角即可分享
微信分享提示