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.效果

相关推荐
桃园码工6 分钟前
8_HTML5 SVG (4) --[HTML5 API 学习之旅]
html5·svg·滤镜·文本·stroke
前端没钱20 分钟前
从 Vue 迈向 React:平滑过渡与关键注意点全解析
前端·vue.js·react.js
汪洪墩24 分钟前
【Mars3d】设置backgroundImage、map.scene.skyBox、backgroundImage来回切换
开发语言·javascript·python·ecmascript·webgl·cesium
NoneCoder25 分钟前
CSS系列(29)-- Scroll Snap详解
前端·css
无言非影29 分钟前
vtie项目中使用到了TailwindCSS,如何打包成一个单独的CSS文件(优化、压缩)
前端·css
我曾经是个程序员1 小时前
鸿蒙学习记录
开发语言·前端·javascript
羊小猪~~1 小时前
前端入门之VUE--ajax、vuex、router,最后的前端总结
前端·javascript·css·vue.js·vscode·ajax·html5
摸鱼了1 小时前
🚀 从零开始搭建 Vue 3+Vite+TypeScript+Pinia+Vue Router+SCSS+StyleLint+CommitLint+...项目
前端·vue.js
程序员shen1616112 小时前
抖音短视频saas矩阵源码系统开发所需掌握的技术
java·前端·数据库·python·算法
Ling_suu2 小时前
SpringBoot3——Web开发
java·服务器·前端