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

相关推荐
摇头的金丝猴15 分钟前
uniapp vue3 使用echarts-gl 绘画3d图表
前端·uni-app·echarts
清清ww27 分钟前
【TS】九天学会TS语法---计划篇
前端·typescript
南棱笑笑生1 小时前
20241105编译Rockchip原厂的Android13并给荣品PRO-RK3566开发板刷机
java·开发语言·前端
dy17171 小时前
el-date-picker日期选择器动态设置日期
前端·vue.js·elementui
浏览器爱好者1 小时前
Chrome与火狐哪个浏览器的性能表现更好
前端·chrome
Topstip1 小时前
在 Google Chrome 上查找并安装 SearchGPT 扩展
前端·人工智能·chrome·gpt·ai·chatgpt
gqkmiss1 小时前
Chrome 130 版本开发者工具(DevTools)更新内容
前端·chrome·chrome devtools·开发者工具·chrome 130
codeGoogle1 小时前
计算机书籍打包
前端·后端·编程语言
小远yyds2 小时前
跨平台使用高德地图服务
前端·javascript·vue.js·小程序·uni-app
weixin_516875652 小时前
使用 axios 拦截器实现请求和响应的统一处理(附常见面试题)
前端·javascript·vue.js