欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

window.print铺满纸张打印

程序员文章站 2022-06-14 08:17:55
...

问题

打印A和B两个区域, 高度大于一张A4纸高度, 如何保证两个区域分别铺满在A4纸
A4纸宽度: 210mm; 高度:297mm;

window.print铺满纸张打印

普通打印:

window.print铺满纸张打印window.print铺满纸张打印

思路:

打印内容超出一张纸高度时,根据纸张大小,设置打印区域的zoom,按比例缩小打印

依赖函数

Print.js,采用iframe绘制并打印 (复制调用即可)

/***** iframe打印
 * @param dom            打印区域的class, id
 * @param options.margin  控制页眉页脚, 默认 4mm
 * @param options.padding 打印边距, 默认 '0 0'
 * @method options.afterprint 打印结束后回调
 * @method options.cancel 取消打印后回调
 * 
 * **/


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>";
    
    str += `<style>
    @media print { 
      @page { margin: ${this.options.margin || '4mm'}; padding: ${this.options.padding || '0 0'}; width:210mm;height:290mm} 
      body {  
        -webkit-print-color-adjust:exact;-moz-print-color-adjust:exact;-ms-print-color-adjust:exact;print-color-adjust:exact; 
      } 
    }
    </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.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() {
      w.onbeforeprint = _this.options.beforeprint;
      w.onafterprint = _this.options.afterprint;
      // iframe.contentWindow.print();
      _this.toPrint(w);
      setTimeout(function() {
        document.body.removeChild(iframe);
      }, 100);
    };
  },

  toPrint: function(frameWindow) {
    var _t = this;
    try {
      setTimeout(function() {
        frameWindow.focus();
        try {
          if (!frameWindow.document.execCommand("print", false, null)) {
            
            frameWindow.print();
          }
        } catch (e) {
          
          frameWindow.print();
        }
        frameWindow.close();
        typeof _t.options.cancel === "function" && _t.options.cancel();
        frameWindow.onbeforeprint = null;
        frameWindow.onafterprint = null;
      }, 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"
          );
        },
};
export default Print 

unitChange.js, px - mm 单位互相转换函数 (复制调用即可)

//  px <-> mm  单位互相转换

/**
 * 获取DPI 每英寸像素点
 * @returns {Array}
 */
let conversion_getDPI = function() {
  var DPI = 0;
  if (window.screen.deviceXDPI) {
    DPI = window.screen.deviceXDPI;
  } else {
    var tmpNode = document.createElement("DIV");
    tmpNode.style.cssText =
      "width:1in;height:1in;position:absolute;left:0px;top:0px;z-index:99;visibility:hidden";
    document.body.appendChild(tmpNode);
    DPI = parseInt(tmpNode.offsetWidth); 
    tmpNode.parentNode.removeChild(tmpNode);
  } 
  return DPI;
};

// 1 英寸=25.4 毫米

/**
 * px转换为mm
 * @param value
 * @returns {number}
 */
let px2mm = function(value) {
  var inch = value / conversion_getDPI();
  var c_value = inch * 25.4;
  //      console.log(c_value);
  return c_value;
};

/**
 * mm转换为px
 * @param value
 * @returns {number}
 */
let mm2px = function(value) {
  var inch = value / 25.4;
  var c_value = inch * conversion_getDPI();
  //      console.log(c_value);
  return c_value;
};
export default {
    mm2px,
    px2mm
};

解决问题

两个区域分别铺满纸张打印:

window.print铺满纸张打印window.print铺满纸张打印
<template>
  <div
    style="
      height: 100%;
      display: flex;
      flex-direction: column;
      width: 210mm;
      align-items: flex-end;
    "
  >
    <button style="padding: 0 10px" @click="doprint">分页铺满纸打印</button>
    <div id="printContent">
      <div class="ctx" style="height: 320mm; background: pink">
        我是打印的内容A
      </div>
      <div class="ctx" style="height: 320mm; background: #6dcc16">
        我是打印的内容B
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
#printContent {
  flex: 1;

  width: 210mm;
  overflow: auto;
  .ctx {
    color: #000;
    width: 100%;
    writing-mode: vertical-lr;
    text-align: center;
    display: flex;
    align-items: center;
    font-size: 60px;
    justify-content: center;
    border: 5px solid blue;
  }
}
</style>

<script>
import unitChange from "@/utils/unitChange.js";
import Print from "@/utils/Print.js";

export default {
  data() {
    return {
      zoomStatus: false,
    };
  },
  methods: {
    doprint() {
      this.setPrintStyle();
      Print("#printContent", {
        afterprint: () => {},
        cancel: () => {},
      });
    },
    //打印区域分页并铺满A4纸打印
    setPrintStyle() {
      if (this.zoomStatus) return;
      this.zoomStatus = true;
      // 保证打印正好铺满A4高度
      let A4height = 297; // A4高度297mm
      let ctxpage = document.querySelectorAll(".ctx");
      ctxpage.forEach((i, k) => {
        let eachpage_mm = unitChange.px2mm(i.clientHeight); // 单位px转mm
        console.log(k + "页高度px:", i.clientHeight, "高度mm:", eachpage_mm);

        //高度大于A4,则按比例缩小打印区域
        if (eachpage_mm > A4height) {
          let zoom = A4height / eachpage_mm;
          console.log(k + "页zoom:", zoom);
          i.style.zoom = zoom;
        }
      });
    },
  },
};


</script>