欢迎来到科站长!

JavaScript

当前位置: 主页 > 网络编程 > JavaScript

前端实现打印网页内容的解决方案(附完整代码)

时间:2025-02-08 10:49:16|栏目:JavaScript|点击:

目录

技术实现:

打印方法通过js原生封装,

框架采用的是vue和elementplus(单纯想实验一下打印方法的可以不用,直接复制下方代码块即可)

实现逻辑:

1.函数入口printHtml,传入对应的参数,节点,缩放比例(可以使百分比或数字 但不能为负)以及覆盖样式。

2.样式设置: 调用 getStyle 函数以获取打印相关的样式,并传入缩放比例和覆盖样式。

3.容器创建: 调用 getContainer 函数,将需要打印的 HTML 内容放入一个新的 DOM 元素(div)添加到文档: 将样式和内容容器添加到 body 中以便于打印。

4.加载图片: 调用 getLoadPromise 函数确保所有图片加载完成后,才触发打印操作。打印完成后清理: 打印完成后,移除添加的样式和内容容器。

封装方法代码如下:

export default function printHtml(
  html: any,
  zoom?: any,
  overrideStyle?: string
) {
  const style = getStyle(zoom, overrideStyle);
  const container = getContainer(html);
  document.body.appendChild(style);
  document.body.appendChild(container);

  getLoadPromise(container).then(() => {
    window.print();
    document.body.removeChild(style);
    document.body.removeChild(container);
  });
}
function getStyle(zoom?: any, overrideStyle?: string) {
  const styleContent =
    `
    #print-container {
      display: none;
      zoom:${zoom ?? "normal"};
    }
  
    @media print {
        body > :not(.print-container) {
            display: none;
        }
        html,
        body {
            display: block !important;
        }
        body {
          height:auto;
        }
        #print-container {
            display: block;
        }
  
    }` + overrideStyle;
  const style = document.createElement("style");
  style.innerHTML = styleContent;
  return style;
}
function cleanPrint() {
  const div = document.getElementById("print-container");
  if (!!div) {
    document.querySelector("body")?.removeChild(div);
  }
}
function getContainer(html: any) {
  cleanPrint();
  const container = document.createElement("div");
  container.setAttribute("id", "print-container");
  container.innerHTML = html;
  return container;
}
function getLoadPromise(dom: any) {
  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: any) => {
      img.addEventListener("load", check);
      img.addEventListener("error", check);
    });
  });
}

调用:

具体调用可以参考一下下方的vue代码,我是将打印的内容放入到自己二次封装的弹框中去了





实现效果如下:

总结

到此这篇关于前端实现打印网页内容解决方案的文章就介绍到这了,更多相关前端打印网页内容内容请搜索科站长以前的文章或继续浏览下面的相关文章希望大家以后多多支持科站长!

上一篇:Vue出现首屏白屏的六种解决方法小结

栏    目:JavaScript

下一篇:基于JS实现右侧缓慢弹窗动态效果

本文标题:前端实现打印网页内容的解决方案(附完整代码)

本文地址:https://www.fushidao.cc/wangluobiancheng/3184.html

广告投放 | 联系我们 | 版权申明

申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:257218569 | 邮箱:257218569@qq.com

Copyright © 2018-2025 科站长 版权所有冀ICP备14023439号