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

相关文章

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

python实现对数据公钥加密与私钥解密

《python实现对数据公钥加密与私钥解密》这篇文章主要为大家详细介绍了如何使用python实现对数据公钥加密与私钥解密,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录公钥私钥的生成使用公钥加密使用私钥解密公钥私钥的生成这一部分,使用python生成公钥与私钥,然后保存在两个文

浏览器插件cursor实现自动注册、续杯的详细过程

《浏览器插件cursor实现自动注册、续杯的详细过程》Cursor简易注册助手脚本通过自动化邮箱填写和验证码获取流程,大大简化了Cursor的注册过程,它不仅提高了注册效率,还通过友好的用户界面和详细... 目录前言功能概述使用方法安装脚本使用流程邮箱输入页面验证码页面实战演示技术实现核心功能实现1. 随机