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