lis8.0-vue3/src/utils/classCom.ts

113 lines
3.1 KiB
TypeScript
Raw Normal View History

2025-08-28 17:47:20 +08:00
/**
* 颜色处理工具类
* 提供十进制颜色值转十六进制颜色码(支持BGR转RGB)及文字对比度计算功能
*/
function decimalToHexColor(decimal: number | string): string {
// 处理空值和非数字情况
if (decimal === undefined || decimal === null || decimal === '') {
return '#FFFFFF';
}
// 统一转换为数字类型
const num = typeof decimal === 'string' ? parseFloat(decimal) : decimal;
2025-08-28 17:47:20 +08:00
if (isNaN(num)) {
return '#FFFFFF';
}
// 十进制转十六进制并转为大写
let hex = Math.floor(num).toString(16).toUpperCase();
let rgbHex = ''
2025-08-28 17:47:20 +08:00
// 确保十六进制字符串为6位,不足则补0
if (hex.length < 6) {
hex = hex.padStart(6, '0');
}
// BGR转RGB(交换前后两位)
const r = hex.substring(4, 6);
const g = hex.substring(2, 4);
const b = hex.substring(0, 2);
rgbHex = r + g + b;
2025-08-28 17:47:20 +08:00
return `#${rgbHex}`;
}
// 处理颜色转换为十进制数字
const convertHexToNumber = (hex: string) => {
if (!hex) return
hex = hex.replace('#', '');
const bgr = hex.slice(4, 6) + hex.slice(2, 4) + hex.slice(0, 2);
return parseInt(bgr, 16);
};
2025-08-28 17:47:20 +08:00
/**
* 根据背景色计算对比度文字颜色(黑/白)
* @param bgColor 十六进制背景色(如#FFFF80)
* @returns 对比度文字颜色(#333333或#FFFFFF)
*/
function getContrastTextColor(bgColor: string): string {
// 验证颜色格式
if (!/^#([0-9A-F]{6})$/i.test(bgColor)) {
throw new Error('Invalid hex color format. Expected #RRGGBB');
}
// 提取RGB分量
const r = parseInt(bgColor.slice(1, 3), 16);
const g = parseInt(bgColor.slice(3, 5), 16);
const b = parseInt(bgColor.slice(5, 7), 16);
// 计算亮度(标准 luminance 公式)
const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
// 根据亮度返回对比色
return luminance > 0.5 ? '#333333' : '#FFFFFF';
}
2025-09-26 17:26:06 +08:00
// 打印https pdf
function printPDF(pdfUrl: string) {
// 验证URL是否为HTTPS
if (pdfUrl.startsWith('http')) {
console.warn('PDF URL不是HTTPS协议,可能存在安全风险');
}
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = pdfUrl;
document.body.appendChild(iframe);
iframe.onload = () => {
iframe.contentWindow?.print();
setTimeout(() => URL.revokeObjectURL(pdfUrl), 1000); // 释放内存
};
}
// 打印base64 pdf
2025-09-26 17:26:06 +08:00
function printBase64PDF(base64: string) {
const blob = base64ToBlob(base64);
const pdfUrl = URL.createObjectURL(blob);
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = pdfUrl;
document.body.appendChild(iframe);
iframe.onload = () => {
iframe.contentWindow?.print();
setTimeout(() => URL.revokeObjectURL(pdfUrl), 1000); // 释放内存
};
}
function base64ToBlob(base64: string) {
const binaryString = atob(base64.replace(/[\n\r]/g, ''));
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return new Blob([bytes], { type: 'application/pdf' });
}
2025-08-28 17:47:20 +08:00
2025-09-26 17:26:06 +08:00
export const classCom = { decimalToHexColor, convertHexToNumber, getContrastTextColor, printBase64PDF, printPDF }
2025-08-28 17:47:20 +08:00