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

index.html

javascript 复制代码
<!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.效果

相关推荐
蒟蒻的贤21 分钟前
vue学习11.21
javascript·vue.js·学习
初遇你时动了情1 小时前
uniapp 城市选择插件
开发语言·javascript·uni-app
zhangjr05752 小时前
【HarmonyOS Next】鸿蒙实用装饰器一览(一)
前端·harmonyos·arkts
不爱学习的YY酱2 小时前
【操作系统不挂科】<CPU调度(13)>选择题(带答案与解析)
java·linux·前端·算法·操作系统
zongzi_4942 小时前
二次封装的天气时间日历选择组件
开发语言·javascript·ecmascript
木子七2 小时前
vue2-vuex
前端·vue
麻辣_水煮鱼2 小时前
vue数据变化但页面不变
前端·javascript·vue.js
BY—-组态2 小时前
web组态软件
前端·物联网·工业互联网·web组态·组态
一条晒干的咸魚2 小时前
【Web前端】实现基于 Promise 的 API:alarm API
开发语言·前端·javascript·api·promise
WilliamLuo3 小时前
MP4结构初识-第一篇
前端·javascript·音视频开发