当前位置: 代码网 > it编程>编程语言>Javascript > 前端实现打印网页内容的解决方案(附完整代码)

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

2025年02月13日 Javascript 我要评论
技术实现:打印方法通过js原生封装,框架采用的是vue和elementplus(单纯想实验一下打印方法的可以不用,直接复制下方代码块即可)实现逻辑:1.函数入口printhtml,传入对应的参数,节点

技术实现:

打印方法通过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代码,我是将打印的内容放入到自己二次封装的弹框中去了

<template>
  <elbutton type="primary" @click="visible = true">喚起打印推弹框</elbutton>
  <promodal v-model:visible="visible" title="打印" @ok="success">
    <div id="mycontent" :style="mycontent">
      <div class="header">居民个人信息</div>
      <eldescriptions
        title="无耻之徒"
        direction="vertical"
        :column="4"
        :size="'default'"
        border
        class="table"
      >
        <eldescriptionsitem label="username"
          >伊恩加拉格</eldescriptionsitem
        >
        <eldescriptionsitem label="telephone"
          >18100000000</eldescriptionsitem
        >
        <eldescriptionsitem label="place" :span="2"
          >南区</eldescriptionsitem
        >
        <eldescriptionsitem label="remarks">
          <eltag size="small">school</eltag>
        </eldescriptionsitem>
        <eldescriptionsitem label="address">
          no.1188, wuzhong avenue, wuzhong district, suzhou, jiangsu province
        </eldescriptionsitem>
      </eldescriptions>
    </div>
  </promodal>
</template>
<script setup lang="ts">
import { proselect, promodal } from "@/components/procomponents/index";
import { ref } from "vue";
import { elbutton, eldescriptions, eldescriptionsitem ,eltag } from "element-plus";
import printhtml from "@/utils/print";

const visible = ref(false);

const mycontent: any = {
  wordbreak: "break-all",
  padding: "0 30px 50px 30px",
  color: "#000",
  fontfamily: "宋体",
  maxheight: window.screen.availheight * 0.6,
  overflowy: "auto",
};

//執行打印
const success = () => {
  printhtml(window.document.getelementbyid(`mycontent`)?.innerhtml ?? "");
};

const updateselect = (val: any) => {
  console.log(val);
  val.foreach((item: any) => {
    console.log(item);
  });
};
</script>

<style lang="less" scoped>
.header {
  text-align: center;
  font-size: 24px;
  margin-bottom: 20px;
  font-weight: bold;
}

.table {
  margin: 0 auto;
}
</style>

实现效果如下:

总结 

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com