当前位置: 首页 > news >正文

vue3 前端实现pdf打印预览 printjs

在这里插入图片描述

  1. 在utils建print.ts文件
interface PrintFunction {extendOptions: Function;getStyle: Function;setDomHeight: Function;toPrint: Function;
}const Print = function (dom, options?: object): PrintFunction {options = options || {};// @ts-expect-errorif (!(this instanceof Print)) return new Print(dom, options);this.conf = {styleStr: "",// Elements that need to dynamically get and set the heightsetDomHeightArr: [],// Callback before printingprintBeforeFn: null,// Callback after printingprintDoneCallBack: null};for (const key in this.conf) {// eslint-disable-next-line no-prototype-builtinsif (key && options.hasOwnProperty(key)) {this.conf[key] = options[key];}}if (typeof dom === "string") {this.dom = document.querySelector(dom);} else {this.dom = this.isDOM(dom) ? dom : dom.$el;}if (this.conf.setDomHeightArr && this.conf.setDomHeightArr.length) {this.setDomHeight(this.conf.setDomHeightArr);}this.init();
};Print.prototype = {/*** init*/init: function (): void {const content = this.getStyle() + this.getHtml();this.writeIframe(content);},/*** Configuration property extension* @param {Object} obj* @param {Object} obj2*/extendOptions: function <T>(obj, obj2: T): T {for (const k in obj2) {obj[k] = obj2[k];}return obj;},/**Copy all styles of the original page*/getStyle: function (): string {let str = "";const styles: NodeListOf<Element> = document.querySelectorAll("style,link");for (let i = 0; i < styles.length; i++) {str += styles[i].outerHTML;}str += `<style>.no-print{display:none;}${this.conf.styleStr}</style>`;return str;},// form assignmentgetHtml: function (): Element {const inputs = document.querySelectorAll("input");const selects = document.querySelectorAll("select");const textareas = document.querySelectorAll("textarea");const canvass = document.querySelectorAll("canvas");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") {const child = selects[k3].children;for (const i in child) {if (child[i].tagName == "OPTION") {if ((child[i] as any).selected == true) {child[i].setAttribute("selected", "selected");} else {child[i].removeAttribute("selected");}}}}}for (let k4 = 0; k4 < canvass.length; k4++) {const imageURL = canvass[k4].toDataURL("image/png");const img = document.createElement("img");img.src = imageURL;img.setAttribute("style", "max-width: 100%;");img.className = "isNeedRemove";canvass[k4].parentNode.insertBefore(img, canvass[k4].nextElementSibling);}return this.dom.outerHTML;},/**create iframe*/writeIframe: function (content) {let w: Document | Window;let doc: Document;const iframe: HTMLIFrameElement = document.createElement("iframe");const f: HTMLIFrameElement = document.body.appendChild(iframe);iframe.id = "myIframe";iframe.setAttribute("style","position:absolute;width:0;height:0;top:-10px;left:-10px;");// eslint-disable-next-line prefer-constw = f.contentWindow || f.contentDocument;// eslint-disable-next-line prefer-constdoc = f.contentDocument || f.contentWindow.document;doc.open();doc.write(content);doc.close();const removes = document.querySelectorAll(".isNeedRemove");for (let k = 0; k < removes.length; k++) {removes[k].parentNode.removeChild(removes[k]);}// eslint-disable-next-line @typescript-eslint/no-this-aliasconst _this = this;iframe.onload = function (): void {// Before popping, callbackif (_this.conf.printBeforeFn) {_this.conf.printBeforeFn({ doc });}_this.toPrint(w);setTimeout(function () {document.body.removeChild(iframe);// After popup, callbackif (_this.conf.printDoneCallBack) {_this.conf.printDoneCallBack();}}, 100);};},/**Print*/toPrint: function (frameWindow): void {try {setTimeout(function () {frameWindow.focus();try {if (!frameWindow.document.execCommand("print", false, null)) {frameWindow.print();}} catch (e) {frameWindow.print();}frameWindow.close();}, 10);} catch (err) {console.error(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");},/*** Set the height of the specified dom element by getting the existing height of the dom element and setting* @param {Array} arr*/setDomHeight(arr) {if (arr && arr.length) {arr.forEach(name => {const domArr = document.querySelectorAll(name);console.log(name, domArr);domArr.forEach(dom => {dom.style.height = dom.offsetHeight + "px";});});}}
};export default Print;
  1. .vue页面使用
    html
    <div class="w-full p-1" id="printApply" style="overflow: auto"><div class="text-center text-2xl">江苏微导纳米股份有限公司</div><div class="text-center text-xl mb-6 mt-2">工具出库单</div><div class="flex"><div class="flex-1 mb-2"><div class="mb-3">事业部:{{ dataSource.chargeDept }}</div><div class="mb-3">班组: {{ dataSource.groupName }}</div><div class="">联系人: ____________________</div></div><div class="flex-1 mb-2"><div class="mb-3">申请人:{{ dataSource.applicant }}</div><div class="mb-3">申请部门:{{ dataSource.applicantDept }}</div><div class="">联系电话: _____________________</div></div><div class="flex-1 mb-2"><div class="mb-3">工具属性:{{ dataSource.toolProperty }}</div><div class="mb-3">工厂: {{ dataSource.factoryName }}</div></div></div><div class="my-3 w-full"><table><colgroup><col width="50" /><col width="120" /><col width="150" /><col width="150" /><col width="100" /><col width="100" /><col width="100" /><col width="100" /></colgroup><tbody><tr height="32" class=""><td class="text-center font-bold">序号</td><td class="text-center font-bold">存货编码</td><td class="text-center font-bold">存货名称</td><td class="text-center font-bold">需求时间</td><td class="text-center font-bold">重要程度</td><td class="text-center font-bold">请购用途</td><td class="text-center font-bold">规格型号</td><!-- <td class="text-center font-bold">工具大类</td> --><td class="text-center font-bold">申领数量</td></tr><template v-for="(item, index) in dataSource.lists"><tr height="32"><td class="text-center">{{ index+1 }}</td><td class="text-center">{{ item.cInvCode }}</td><td class="text-center">{{ item.cInvName }}</td><td class="text-center">{{ item.demandTime&&item.demandTime.slice(0, 10) }}</td><td class="text-center">{{ item.significance }}</td><td class="text-center">{{ item.purpose }}</td><td class="text-center">{{ item.cInvStd }}</td><!-- <td class="text-center">{{ item.toolType }}</td> --><td class="text-center">{{ item.applicationQty }}</td></tr></template><tr height="32"><td class="text-center font-bold">合计:</td><td colspan="6" class="text-left"></td><td class="text-center">{{sum}}</td></tr><tr height="65"><td colspan="8" class="text-left ">备注:<br />1、请双方确认无误后签字确认,谢谢!</td></tr></tbody></table></div><div class="w-4/5 mt-2 flex justify-around"><div class=""><div class="">发起人签字:</div><div class="mt-2">发起日期:</div></div><div class=""><div class="">审批人签字:</div><div class="mt-2">审批日期:</div></div></div></div>

css

#printApply {display: none;
}
// 设置打印的时候,显示
#printApply {@media print {display: block;}
}#printApply table {border-top: 1px solid #333;border-left: 1px solid #333;border-spacing: 0;background-color: #fff;width: 100%;
}
#printApply table td {border-bottom: 1px solid #333;border-right: 1px solid #333;font-size: 14px;padding: 5px;
}

ts

import {Printer
} from "@element-plus/icons-vue";
import Print from "@/utils/print";const dataSource = ref({chargeDept: "",groupName: "",applicant: "",applicantDept: "",toolProperty: "",factoryName: "",lists: []
})
let sum = 0
const handlePrint = async (row) => {sum = 0dataSource.value = rowdataSource.value.lists.forEach((item) => {sum += item.applicationQty})setTimeout(() => {Print("#printApply").toPrint;},500)
};

注意:在主页面打印 需要给#printApply设置隐藏 设置打印的时候,再显示,即

#printApply {display: none;
}
#printApply {@media print {display: block;}
}

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • spring boot(学习笔记第十九课)
  • F12抓包03:设置网速(弱网测试)
  • 开放式耳机的优缺点?有什么推荐吗?四款开放式蓝牙耳机推荐
  • JavaScript网页设计案例
  • 微信小程序代码 app.json文件详细介绍
  • 前端算法面试题1--栈、队列、链表、字典与哈希表
  • Apache Pig
  • 快速便捷地解决 reCAPTCHA 的方法
  • 【Python深度学习】增量学习
  • ICMP协议(介绍,类型),ping命令原理+注意点,traceroute原理(原始套接字)
  • 精密五金零配件加工的核心技术解析
  • SQL 中 LIKE 和 REGEXP 的相同点与不同点解析
  • Verilog基础,原码,反码与补码的概念
  • 乐鑫ESP-HMI方案人机交互,设备彩屏显示新体验,启明云端乐鑫代理商
  • [Linux]:权限
  • [译] 理解数组在 PHP 内部的实现(给PHP开发者的PHP源码-第四部分)
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 【跃迁之路】【585天】程序员高效学习方法论探索系列(实验阶段342-2018.09.13)...
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • AngularJS指令开发(1)——参数详解
  • C语言笔记(第一章:C语言编程)
  • django开发-定时任务的使用
  • JavaScript 基本功--面试宝典
  • JavaScript函数式编程(一)
  • javascript数组去重/查找/插入/删除
  • Phpstorm怎样批量删除空行?
  • react-native 安卓真机环境搭建
  • TCP拥塞控制
  • Vue2.0 实现互斥
  • Yii源码解读-服务定位器(Service Locator)
  • 开放才能进步!Angular和Wijmo一起走过的日子
  • 前端学习笔记之原型——一张图说明`prototype`和`__proto__`的区别
  • 原生JS动态加载JS、CSS文件及代码脚本
  • Play Store发现SimBad恶意软件,1.5亿Android用户成受害者 ...
  • ​LeetCode解法汇总2670. 找出不同元素数目差数组
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • ‌JavaScript 数据类型转换
  • ###项目技术发展史
  • #C++ 智能指针 std::unique_ptr 、std::shared_ptr 和 std::weak_ptr
  • #Datawhale AI夏令营第4期#AIGC方向 文生图 Task2
  • #if 1...#endif
  • #使用清华镜像源 安装/更新 指定版本tensorflow
  • #数学建模# 线性规划问题的Matlab求解
  • (C11) 泛型表达式
  • (C语言)求出1,2,5三个数不同个数组合为100的组合个数
  • (delphi11最新学习资料) Object Pascal 学习笔记---第14章泛型第2节(泛型类的类构造函数)
  • (k8s)Kubernetes本地存储接入
  • (二)Kafka离线安装 - Zookeeper下载及安装
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (十八)SpringBoot之发送QQ邮件
  • (转)shell调试方法
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .net core 6 redis操作类
  • .net core 连接数据库,通过数据库生成Modell
  • .NET MAUI Sqlite数据库操作(二)异步初始化方法