当前位置: 首页 > article >正文

js中怎么把excel和pdf文件转换成图片打包下载

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件转图片工具</title>
    <!-- 本地引入 -->
    <!-- <script src="js/xlsx.full.min.js"></script>
    <script src="js/html2canvas.min.js"></script>
    <script src="js/jszip.min.js"></script>
    <script src="js/pdf.js"></script>
    <script src="js/pdf.worker.js"></script> -->
    <!-- cdn引入 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.0/xlsx.full.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
</head>

<body>
    <input type="file" id="fileInput" accept=".xlsx,.xls,.pdf">
    <button id="excel-download" onclick="downloadexcel()" style="display:none;">excel转换并下载</button>
    <button id="zip-download" style="display:none;" onClick="downloadPdf()">pdf转换并下载</button>
    <div id="excelContent" class="camvasClass"></div>
    <div id="image-container"></div>
    <script>
        let SheetNamesList = [];
        let fileName = '';
        let zip = new JSZip();
        let file = {};

        // excel转图片
        document.getElementById('fileInput').addEventListener('change', function (event) {
            file = event.target.files[0];
            fileName = file.name.split('.')[0];
            if (!file || file.type !== 'application/pdf') {
                renderExcel()
            } else {
                renderPdf()
            }
        });
        // excel转图片并打包为zip  
        function renderExcel() {  
            const reader = new FileReader();  
            reader.onload = function (e) {  
                const data = new Uint8Array(e.target.result);  
                const workbook = XLSX.read(data, { type: 'array' });  
                SheetNamesList = workbook.SheetNames;  
                const zip = new JSZip(); // 初始化JSZip实例  
                SheetNamesList.forEach((sheetName, index) => {  
                    const worksheet = workbook.Sheets[sheetName];  
                    const html = XLSX.utils.sheet_to_html(worksheet);  
                    const divDom = document.createElement('div');  
                    divDom.id = 'sheetDiv' + index;  
                    divDom.innerHTML = html;  
                    document.getElementById('excelContent').appendChild(divDom);  
  
                    // 使用html2canvas将div转换为图片,并添加到zip中  
                    html2canvas(divDom).then(async canvas => {  
                        const imgDataUrl = canvas.toDataURL('image/png');  
                        const imgBlob = (await (await fetch(imgDataUrl)).blob());  
                        zip.file(sheetName + '.png', imgBlob);  
  
                        // 检查是否所有图片都已处理完毕  
                        if (index === SheetNamesList.length - 1) {  
                            // 所有图片都已处理完毕,生成并下载zip文件  
                            zip.generateAsync({ type: 'blob' }).then(blob => {  
                                const url = URL.createObjectURL(blob);  
                                const a = document.createElement('a');  
                                a.href = url;  
                                a.download = fileName + '.zip';  
                                document.body.appendChild(a);  
                                a.click();  
                                document.body.removeChild(a);  
                                URL.revokeObjectURL(url);  
                            });  
                        }  
                    });  
                });  
            };  
            reader.readAsArrayBuffer(file);  
        }
        // pdf转图片
        function renderPdf() {
            const reader = new FileReader();
            reader.onload = async function (e) {
                const arrayBuffer = e.target.result;
                const uint8Array = new Uint8Array(arrayBuffer);

                const pdf = await pdfjsLib.getDocument({ data: uint8Array }).promise;
                const numPages = pdf.numPages;
                const imageContainer = document.getElementById('image-container');
                const zipDownloadButton = document.getElementById('zip-download');
                const promises = [];
                for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
                    promises.push(new Promise(async (resolve, reject) => {
                        try {
                            const page = await pdf.getPage(pageNumber);
                            const viewport = page.getViewport({ scale: 1.5 });
                            const canvas = document.createElement('canvas');
                            const context = canvas.getContext('2d');
                            canvas.width = viewport.width;
                            canvas.height = viewport.height;

                            await page.render({ canvasContext: context, viewport }).promise;

                            // 将canvas内容转换为DataURL  
                            const imgDataUrl = canvas.toDataURL('image/png');

                            // const img = document.createElement('img')
                            // img.src = imgDataUrl
                            // imageContainer.appendChild(img)

                            // 创建一个Blob对象  
                            const imgBlob = await (await fetch(imgDataUrl)).blob();

                            // 将Blob对象添加到ZIP中  
                            zip.file(`${fileName}_page_${pageNumber}.png`, imgBlob);

                            // 可选:显示图片和下载链接(这里不再需要,因为只是为了生成ZIP)  
                            // ... (省略显示图片和创建下载链接的代码)  

                            resolve();
                        } catch (error) {
                            reject(error);
                        }
                    }));
                }

                try {
                    // 等待所有页面都处理完毕  
                    await Promise.all(promises);
                    // 显示下载ZIP按钮(如果需要的话,这里可以省略,因为已经下载了)  
                    zipDownloadButton.style.display = 'inline-block';

                } catch (error) {
                    console.error('Error generating ZIP:', error);
                }
            };
            reader.readAsArrayBuffer(file); // 读取文件为ArrayBuffer  
        }



        async function downloadPdf() {
            // 生成ZIP文件并触发下载  
            const zipBlob = await zip.generateAsync({ type: 'blob' });
            const zipUrl = URL.createObjectURL(zipBlob);

            const a = document.createElement('a');
            a.href = zipUrl;
            a.download = fileName+'.zip';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            // 清理  
            URL.revokeObjectURL(zipUrl);
        }

    </script>
    <style>
        #excelContent {
            padding: 20px;
        }

        .pb20 {
            padding-bottom: 40px;
        }
    </style>
</body>

</html>

2.效果


http://www.kler.cn/a/385036.html

相关文章:

  • 中肿团队提出的“免疫三明治”(放疗+化疗+免疫治疗),成功登上柳叶刀肿瘤|顶刊精析·24-11-08
  • JS实现,防抖节流 + 闭包
  • Python使用PDF相关组件案例详解
  • 信号-2-信号捕捉
  • 信息化运维方案,实施方案,开发方案,信息中心安全运维资料(软件资料word)
  • 人工智能未来前景好不好?
  • 云上拼团GO指南——腾讯云博客部署案例,双11欢乐GO
  • 推导将点映射到平面坐标系的计算公式
  • 金媒婚恋相亲系统10.4择爱开源旗舰版支持微信小程和抖音小程序上架
  • 鸿蒙系统与python
  • 【WebRTC】视频采集模块流程的简单分析
  • 收集的linux命令/Docker命令/git命令
  • 第2章-立项2.5立项的三重境界
  • 【数据集】【YOLO】【目标检测】道路结冰数据集 1527 张,YOLO目标检测实战训练教程!
  • 软件架构演变:从单体架构到LLM链式调用
  • qt QTextCursor详解
  • java的面向对象(从入门到深入)
  • harmony os 四层架构分析
  • Elasticsearch(三):Elasticvue使用及DSL执行新增、查询操作
  • Hive:explode 和 lateral view
  • 算法通关(3) -- kmp算法
  • leetcode155:最小栈
  • Java中怎样将bytes转换为long类型?
  • blender中,渲染是指渲染图片or视频 ,还是模型?
  • 前端开发实现自定义勾选/自定义样式,可复选,可取消勾选
  • Maven的安装配置