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

相关文章

Springboot处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.

Python+PyQt5实现多屏幕协同播放功能

《Python+PyQt5实现多屏幕协同播放功能》在现代会议展示、数字广告、展览展示等场景中,多屏幕协同播放已成为刚需,下面我们就来看看如何利用Python和PyQt5开发一套功能强大的跨屏播控系统吧... 目录一、项目概述:突破传统播放限制二、核心技术解析2.1 多屏管理机制2.2 播放引擎设计2.3 专

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

idea中创建新类时自动添加注释的实现

《idea中创建新类时自动添加注释的实现》在每次使用idea创建一个新类时,过了一段时间发现看不懂这个类是用来干嘛的,为了解决这个问题,我们可以设置在创建一个新类时自动添加注释,帮助我们理解这个类的用... 目录前言:详细操作:步骤一:点击上方的 文件(File),点击&nbmyHIgsp;设置(Setti

SpringBoot实现MD5加盐算法的示例代码

《SpringBoot实现MD5加盐算法的示例代码》加盐算法是一种用于增强密码安全性的技术,本文主要介绍了SpringBoot实现MD5加盐算法的示例代码,文中通过示例代码介绍的非常详细,对大家的学习... 目录一、什么是加盐算法二、如何实现加盐算法2.1 加盐算法代码实现2.2 注册页面中进行密码加盐2.

MySQL大表数据的分区与分库分表的实现

《MySQL大表数据的分区与分库分表的实现》数据库的分区和分库分表是两种常用的技术方案,本文主要介绍了MySQL大表数据的分区与分库分表的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录1. mysql大表数据的分区1.1 什么是分区?1.2 分区的类型1.3 分区的优点1.4 分