/* * @Description: * @Author: xuch * @FilePath: \yuan-qingdao-zld-browser\src\utils\utils.ts * @Date: 2022-08-30 16:16:39 * @LastEditTime: 2023-09-18 17:10:49 * @LastEditors: 李佐宁 */ import { getDictTypeList } from '@/api/common'; import html2canvas from 'html2canvas'; import JsPDF from 'jspdf'; /** * @description: 通用下载 (要求返回文件流) * @param {*} data 数据 * @param {*} name 文件名称 * @param {*} type 文件类型 * @author changjun */ export function downLoadFile(data, name, type = 'xlsx') { // data = if (!data) return; const mimeType = { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xls: 'application/vnd.ms-excel', pdf: 'application/pdf', zip: 'application/x-zip-compressed', csv: 'text/csv', html: 'text/html', }; const blob = new Blob([data], { type: mimeType[type] }); // const blob = new Blob([data], { type: data.type }) const _link = document.createElement('a'); _link.download = name; _link.style.display = 'none'; _link.href = URL.createObjectURL(blob); document.body.appendChild(_link); _link.click(); URL.revokeObjectURL(_link.href); document.body.removeChild(_link); } /** * @description: 获取当前年月日 * @author tqh */ export function getNowFormatDate() { let date = new Date(), seperator1 = '-', //格式分隔符 year = date.getFullYear(), //获取完整的年份(4位) month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月) strDate = date.getDate(); // 获取当前日(1-31) if (month >= 1 && month <= 9) month = '0' + month; // 如果月份是个位数,在前面补0 if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate; // 如果日是个位数,在前面补0 let currentdate = year + seperator1 + month + seperator1 + strDate; return currentdate; } /** * @description: 深度拷贝 * @author tqh */ export function deepCopy(obj) { let target = null; if (typeof obj === 'object') { if (Array.isArray(obj)) { //数组 target = []; obj.forEach((item) => { target.push(deepCopy(item)); }); } else if (obj) { target = {}; let objKeys = Object.keys(obj); objKeys.forEach((key) => { target[key] = deepCopy(obj[key]); }); } else { target = obj; } } else { target = obj; } return target; } /** * @description: 通用下载文件流 * @author tqh */ export function downLoadAllFile(data, fileName, type) { let blob = new Blob([data], { type: `application/${type};charset=utf-8` }); // 获取heads中的filename文件名 let downloadElement = document.createElement('a'); // 创建下载的链接 let href = window.URL.createObjectURL(blob); downloadElement.href = href; // 下载后文件名 downloadElement.download = fileName; document.body.appendChild(downloadElement); // 点击下载 downloadElement.click(); // 下载完成移除元素 document.body.removeChild(downloadElement); // 释放掉blob对象 window.URL.revokeObjectURL(href); } /** * @description: 获取字典 * @param {string} - dictType - 字典类型 * @param {boolean} - same - label和value是否相同 */ export const getDictList = (dictType, same?) => { return new Promise((resolve, reject) => { getDictTypeList({ dictType }).then((res) => { let { code, data = [] } = res || {}; if (code === 200) { data = data || []; data.forEach((item) => { item.value = same ? item.dictName : item.dictValue; item.label = item.dictName; }); resolve(data); } else { reject(res.message); } }); }); }; /** * @param ele 要生成 pdf 的DOM元素(容器) * @param padfName PDF文件生成后的文件名字 * */ export const downloadPDF = (ele: any, pdfName: string): void => { const eleW: number = ele.offsetWidth; // 获得该容器的宽 const eleH: number = ele.offsetHeight; // 获得该容器的高 const eleOffsetTop: number = ele.offsetTop; // 获得该容器到文档顶部的距离 const eleOffsetLeft: number = ele.offsetLeft; // 获得该容器到文档最左的距离 const canvas = document.createElement('canvas'); let abs = 0; const win_in: number = document.documentElement.clientWidth || document.body.clientWidth; // 获得当前可视窗口的宽度(不包含滚动条) const win_out: number = window.innerWidth; // 获得当前窗口的宽度(包含滚动条) if (win_out > win_in) { // abs = (win_o - win_i)/2; // 获得滚动条长度的一半 abs = (win_out - win_in) / 2; // 获得滚动条宽度的一半 // console.log(a, '新abs'); } canvas.width = eleW * 2; // 将画布宽&&高放大两倍 canvas.height = eleH * 2; const context: any = canvas.getContext('2d'); context.scale(2, 2); context.translate(-eleOffsetLeft - abs, -eleOffsetTop); // 这里默认横向没有滚动条的情况,因为offset.left(),有无滚动条的时候存在差值,因此 // translate的时候,要把这个差值去掉 // html2canvas(element).then( (canvas)=>{ //报错 // html2canvas(element[0]).then( (canvas)=>{ html2canvas(ele, { //dpi: 300, // allowTaint: true, //允许 canvas 污染, allowTaint参数要去掉,否则是无法通过toDataURL导出canvas数据的 useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。 }).then((canvas: any) => { const contentWidth: number = canvas.width; const contentHeight: number = canvas.height; //一页pdf显示html页面生成的canvas高度; const pageHeight: number = (contentWidth / 592.28) * 841.89; //未生成pdf的html页面高度 let leftHeight = contentHeight; //页面偏移 let position = 0; //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 const imgWidth = 595.28; const imgHeight = (595.28 / contentWidth) * contentHeight; const pageData = canvas.toDataURL('image/jpeg', 1.0); const pdf = new JsPDF('portrait', 'pt', 'a4'); //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < pageHeight) { //在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示; pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight); // pdf.addImage(pageData, 'JPEG', 20, 40, imgWidth, imgHeight); } else { // 分页 while (leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight); leftHeight -= pageHeight; position -= 841.89; //避免添加空白页 if (leftHeight > 0) { pdf.addPage(); } } } //可动态生成 pdf.save(pdfName); }); }; /** * 根据图片路径判断图片是否存在 * @param path {string} 图片完整路径 * @returns */ export const checkImageExistence = (path) => { return new Promise((resolve, reject) => { const img = new Image(); img.src = path; img.onload = () => { resolve(path); }; img.onerror = () => { resolve(''); }; }); }; /** * 根据图片是否存在 * @param filePath * @returns */ export const checkImagePathExistence = (filePath: string): Promise => { filePath = addVersion(filePath); return new Promise(async (resolve) => { try { const exist = await checkImageExistence(filePath); if (exist) { return resolve(filePath); } } catch (e) {} }); }; /** * 动态添加ico * @param newFavicon ico图标路径 */ export const changeFavicon = (newFavicon) => { const yaFavicon = document.getElementById('yaFavicon'); if (yaFavicon) { yaFavicon.remove(); } var favicon = document.createElement('link'); favicon.rel = 'icon'; favicon.id = 'yaFavicon'; favicon.type = 'image/x-icon'; favicon.href = addVersion(newFavicon); document.head.appendChild(favicon); }; /** * 给文件资源添加版本号 * @param name {string} 文件名称 * @returns */ export const addVersion = (name) => { return name + '?v=' + new Date().getTime(); };