zhanghua
2025-06-13 21c9c72db79cd1cc450d7dfb668cbab43befa991
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
export function loadPrintStyle() {
  let style = getStyle();
  document.body.appendChild(style);
}
 
export function printHtml(html) {
  let container = getContainer(html);
  document.body.appendChild(container);
  getLoadPromise(container).then(() => {
    window.print();
    document.body.removeChild(container);
  });
}
 
 
// 设置打印样式
function getStyle() {
  let styleContent = `#print-container {
      display: none;
  }
  @media print {
      body > :not(.print-container) {
          display: none;
      }
      html,
      body {
          display: block !important;
      }
      #print-container {
          display: block;
      }
  }
      @page {
        margin-top: 0;
        margin-bottom: 0
        }    
`;
  let style = document.createElement("style");
  style.innerHTML = styleContent;
  return style;
}
 
// 清空打印内容
function cleanPrint() {
  let div = document.getElementById('print-container')
  if (!!div) {
    document.querySelector('body').removeChild(div)
  }
}
 
// 新建DOM,将需要打印的内容填充到DOM
function getContainer(html) {
  cleanPrint()
  let container = document.createElement("div");
  container.setAttribute("id", "print-container");
  container.innerHTML = html;
  return container;
}
 
// 图片完全加载后再调用打印方法
function getLoadPromise(dom) {
  let imgs = dom.querySelectorAll("img");
  imgs = [].slice.call(imgs);
 
  if (imgs.length === 0) {
    return Promise.resolve();
  }
 
  let finishedCount = 0;
  return new Promise(resolve => {
    function check() {
      finishedCount++;
      if (finishedCount === imgs.length) {
        resolve();
      }
    }
    imgs.forEach(img => {
      img.addEventListener("load", check);
      img.addEventListener("error", check);
    })
  });
}