获取Word、PPT、Excel、PDF文件页数及加密校验

news/2024/10/18 5:47:54/

想要获取一个pdf文件的页数,有多种实现方式。可以利用pdfjs,也可以利用PDFDocument:

// 方法一:利用文件的arrayBuffer
let arrayBuffer = await file.arrayBuffer();
const pdfDoc = await PDFDocument.load(arrayBuffer, { ignoreEncryption: true });
const pageCount =  pdfDoc.getPageCount();// 方法二:利用文件生成blob对象
const pdfObj = await PDFDocument.load(blob, { ignoreEncryption: true });
const pageCount = pdfObj.getPageCount();// 方法三:利用文件的在线预览地址
const byteString = atob(file.base64.split(',')[1]);
const mimeString = file.base64.split(',')[0].split(':')[1].split(';')[0];
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);
}const loadingTask = pdfjsLib.getDocument({data: ab,password: file.code || '',
});const pdfDocument = await loadingTask.promise;
const pageCount = pdfDocument.numPages;

如果是加密文件,想要使用pdfjs方式获取文件页数,需要提前给用户弹出密码框进行密码输入及验证,如何进行密码验证呢

(office文件暂时没有密码正确性验证的方式,因此只能校验是否是加密文件,而pdf文件可以校验出是否其他权限有无加密)

import { PDFDocument  } from 'pdf-lib';
import '@/assets/pdfjs/build/pdf.js'
import '@/assets/pdfjs/build/pdf.worker.js'
import * as XLSX from 'xlsx';
import JSZip from 'jszip';
import { gaEvent } from '@/utils/gtag'// 判断是否已加密
const checkIfFileEncrypted = async (file: any, isCloud: boolean) => {try {let arrayBuffer;if (isCloud) {const link = await getAccessLink(file.cloudId || file.file_id, file.name || file.file_name);const response = await fetch(link);if (!response.ok) throw new Error('Failed to fetch file');arrayBuffer = await response.arrayBuffer();} else {if(!file.base64) {arrayBuffer = await file.arrayBuffer();} else {const byteString = atob(file.base64.split(',')[1]);const mimeString = file.base64.split(',')[0].split(':')[1].split(';')[0];const ab = new ArrayBuffer(byteString.length);const ia = new Uint8Array(ab);for (let i = 0; i < byteString.length; i++) {ia[i] = byteString.charCodeAt(i);}// 创建 Blobconst blob = new Blob([ab], { type: mimeString });const fileObj = blobToFile(blob, file.name);arrayBuffer = await fileObj.arrayBuffer();}}if (file.type === 'application/pdf' || file.file_type === 'pdf' || file.name.endsWith('.pdf')) {// PDF 文件的加密检查const result = await checkPDFFileEncryption(arrayBuffer);return result.isEncrypted;} else if (file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||file.type === 'application/msword' ||file.file_type === 'docx' ||file.file_type === 'doc') {// Word 文件的加密检查return checkWordFileEncryption(arrayBuffer);} else if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||file.type === 'application/vnd.ms-excel' ||file.file_type === 'xlsx' ||file.file_type === 'xls') {// Excel 文件的加密检查return checkExcelFileEncryption(arrayBuffer);} else if (file.type === 'application/vnd.openxmlformats-officedocument.presentationml.presentation' ||file.type === 'application/vnd.ms-powerpoint' ||file.file_type === 'pptx' ||file.file_type === 'ppt') {// PPT 文件的加密检查return checkPPTFileEncryption(arrayBuffer);} else {return false; // 默认不加密}} catch (error) {return false;}
};// PDF 文件加密检测
const checkPDFFileEncryption = async (arrayBuffer: any) => {try {const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });const pdfDoc = await loadingTask.promise;const permissions = await pdfDoc.getPermissions();if (permissions) {return {isEncrypted: false,hasOwnerPassword: true};}return {isEncrypted: false,hasOwnerPassword: false};} catch (error: any) {if (error.name === 'PasswordException') {return {isEncrypted: true,hasOwnerPassword: false};}return {isEncrypted: false,hasOwnerPassword: false};}
};// 验证 PDF 密码的函数
const verifyPDFPassword = async (file: any, password: string, isCode: boolean) => {try {let arrayBuffer;if (isCode) { // 云盘文件const link = await getAccessLink(file.cloudId || file.file_id, file.name || file.file_name);const response = await fetch(link);if (!response.ok) throw new Error('Failed to fetch file');arrayBuffer = await response.arrayBuffer();} else {arrayBuffer = await file.arrayBuffer();}const loadingTask = pdfjsLib.getDocument({data: arrayBuffer,password: password,});await loadingTask.promise;return true; // 密码正确} catch (error: any) {if (error.name === 'PasswordException') {return false; // 密码错误}return false; // 其他错误}
};// 提示用户输入密码的函数
const promptUserForPassword = async (file: any) => {return new Promise((resolve) => {EventBus.$emit('show-password-prompt', file, (action: any, password: string) => {resolve({ action, password });});});
};// Word 文件加密检测
const checkWordFileEncryption = async (arrayBuffer: any) => {try {const zip = await JSZip.loadAsync(arrayBuffer);if (zip.files['word/document.xml']) {return false; // 文件解压成功,说明未加密}} catch (error: any) {if (error.message.includes('End of data reached') ||error.message.includes('Corrupted zip') ||error.message.includes('Can\'t find end of central directory')) {return true; // 文件加密或损坏}}return false;
};// Excel 文件加密检测
const checkExcelFileEncryption = async (arrayBuffer: any) => {try {const workbook = XLSX.read(arrayBuffer, { type: 'array' });if (workbook.SheetNames.length > 0) {return false; // 文件解压成功,说明未加密}} catch (error: any) {if (error.message.includes('Encrypted') ||error.message.includes('File is password-protected')) {return true; // 文件加密}}return false;
};// PPT 文件加密检测
const checkPPTFileEncryption = async (arrayBuffer: any) => {try {const zip = await JSZip.loadAsync(arrayBuffer);if (zip.files['ppt/presentation.xml']) {return false; // 文件解压成功,说明未加密}} catch (error: any) {if (error.message.includes('Encrypted') ||error.message.includes('Can\'t find end of central directory')) {return true; // 文件加密}}return false;
};

通过以上方式即可成功拿到进行加密校验,下面是word、PPT、Excel格式文件获取文件页数的方式:

// 获取PDF文件页数
const getPDFPageCount = async (arrayBuffer, password) => {const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer, password });const pdfDocument = await loadingTask.promise;return pdfDocument.numPages;
};// 获取Word文件页数
const getWordPageCount = async (arrayBuffer) => {try {const zip = await JSZip.loadAsync(arrayBuffer);if (zip.files['word/document.xml']) {// 解析 document.xml 获取页数(此处仅为示例,具体解析需要更复杂的处理)return 1; // Word文件页数暂时返回1}} catch (error) {console.error('Error processing Word file:', error);}return 1;
};// 获取Excel文件页数
const getExcelPageCount = async (arrayBuffer) => {try {const workbook = XLSX.read(arrayBuffer, { type: 'array' });// 以工作表的数量作为页数return workbook.SheetNames.length;} catch (error) {console.error('Error processing Excel file:', error);}return 1;
};// 获取PPT文件页数
const getPPTPageCount = async (arrayBuffer) => {try {const zip = await JSZip.loadAsync(arrayBuffer);if (zip.files['ppt/slides/']) {// 以幻灯片数量作为页数return Object.keys(zip.files['ppt/slides/']).length;}} catch (error) {console.error('Error processing PPT file:', error);}return 1;
};


http://www.ppmy.cn/news/1518012.html

相关文章

matlab实现模拟退火算法

模拟退火算法&#xff08;Simulated Annealing, SA&#xff09;是一种通用概率优化算法&#xff0c;用于在给定的大搜索空间内寻找问题的近似全局最优解。该算法灵感来源于物理学中固体物质的退火过程&#xff0c;其中温度逐渐降低&#xff0c;粒子逐渐趋于能量最低状态。 在M…

2.5G网络(通常指2.5G以太网,即2500BASE-X)的网络变压器在设计和应用上有几个关键方面

信号传输和接收&#xff1a; 2.5G网络变压器主要用于以太网设备中&#xff0c;用于将信号从平衡转换为非平衡&#xff0c;或者进行阻抗匹配&#xff0c;确保信号能够在传输线和接收器之间有效地传输和接收。 频率范围&#xff1a; 这些变压器需要支持2.5G以太网的频率范围&…

无人机喊话器详解!!!

无人机喊话器&#xff0c;也被称为无人机扬声器&#xff0c;是一种安装在无人机上&#xff0c;用于通过空中向地面人员传递声音的设备。 一、功能特点 远程传递声音&#xff1a;无人机喊话器能够在较远的距离内清晰地传递声音&#xff0c;有效广播范围通常可达数百米甚至更远…

fpga图像处理实战-图像浮雕

图像浮雕 图像浮雕(Embossing)是一种图像处理技术,通过模仿浮雕效果,将二维图像转换为具有三维质感的图像。浮雕效果通常会使图像看起来像是雕刻在某种材质上的图案,具有突出的边缘和阴影,增强了图像的立体感。 图像浮雕特效实现的基本原理 实现图像浮雕特效的算法很多,…

软件防查盗版

信息化发展迅速&#xff0c;企业日常办公越来越依赖互联网。然而终端及普通PC在访问互联网过程中&#xff0c;会面临各种不容忽视的风险。这些风险包括&#xff1a; &#xff08;1&#xff09;员工主动故意的数据泄漏&#xff1a;员工可能故意泄露敏感信息。 &#xff08;2&a…

redisson watchdog 原理

目录 1、使用2、加锁解析1、getLock2、tryLock2.1、当ttl为null时为加锁成功&#xff0c;返回true,否则继续往下执行&#xff0c;判断是否超过等待时间&#xff0c;当前时间减去获取锁前时间就是获取锁花费时间。2.2、tryAcquire(leaseTime, unit, threadId)2.3 、renewExpirat…

【机器学习-监督学习】神经网络与多层感知机

【作者主页】Francek Chen 【专栏介绍】 ⌈ ⌈ ⌈Python机器学习 ⌋ ⌋ ⌋ 机器学习是一门人工智能的分支学科&#xff0c;通过算法和模型让计算机从数据中学习&#xff0c;进行模型训练和优化&#xff0c;做出预测、分类和决策支持。Python成为机器学习的首选语言&#xff0c;…

数据库:笔记03SQL

模式的定义与删除 个关系数据库管理系统的实例&#xff08;instance&#xff09;中可以建立多个数据库&#xff0c;一个数据库中可以建立多个模式&#xff0c;一个模式下通常包括多个表、视图和索引等数据库对象。 定义 CREATE SCHEMA <模式名> AUTHORIZATION <用户…