vue3 前端实现pdf打印预览 printjs

2024-09-05 07:12

本文主要是介绍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;}
}

这篇关于vue3 前端实现pdf打印预览 printjs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138290

相关文章

Vue3 的 shallowRef 和 shallowReactive:优化性能

大家对 Vue3 的 ref 和 reactive 都很熟悉,那么对 shallowRef 和 shallowReactive 是否了解呢? 在编程和数据结构中,“shallow”(浅层)通常指对数据结构的最外层进行操作,而不递归地处理其内部或嵌套的数据。这种处理方式关注的是数据结构的第一层属性或元素,而忽略更深层次的嵌套内容。 1. 浅层与深层的对比 1.1 浅层(Shallow) 定义

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

【 html+css 绚丽Loading 】000046 三才归元阵

前言:哈喽,大家好,今天给大家分享html+css 绚丽Loading!并提供具体代码帮助大家深入理解,彻底掌握!创作不易,如果能帮助到大家或者给大家一些灵感和启发,欢迎收藏+关注哦 💕 目录 📚一、效果📚二、信息💡1.简介:💡2.外观描述:💡3.使用方式:💡4.战斗方式:💡5.提升:💡6.传说: 📚三、源代码,上代码,可以直接复制使用🎥效果🗂️目录✍️

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【专题】2024飞行汽车技术全景报告合集PDF分享(附原数据表)

原文链接: https://tecdat.cn/?p=37628 6月16日,小鹏汇天旅航者X2在北京大兴国际机场临空经济区完成首飞,这也是小鹏汇天的产品在京津冀地区进行的首次飞行。小鹏汇天方面还表示,公司准备量产,并计划今年四季度开启预售小鹏汇天分体式飞行汽车,探索分体式飞行汽车城际通勤。阅读原文,获取专题报告合集全文,解锁文末271份飞行汽车相关行业研究报告。 据悉,业内人士对飞行汽车行业

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo