一般情况下,pdf转图片都是后端来做的,但是前端也可以实现他。通过pdfjs和一些js代码就可以轻松实现。以下是完整的实现代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Convert PDF to Image</title>
</head>
<body>
<form>
<label for="pdf-url">PDF URL:</label>
<input type="text" id="pdf-url" />
<br />
<label for="pdf-file">PDF File:</label>
<input type="file" id="pdf-file" />
<button type="submit">Convert to Image</button>
</form>
<canvas id="pdf-canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js"></script>
<script>
const canvas = document.getElementById("pdf-canvas");
const ctx = canvas.getContext("2d");
const urlField = document.getElementById("pdf-url");
const fileInput = document.getElementById("pdf-file");
document
.querySelector("form")
.addEventListener("submit", function (event) {
event.preventDefault();
if (urlField.value.trim() !== "") {
// 从给定 URL 加载 PDF 文件
loadPdfFromUrl(urlField.value);
} else if (fileInput.files.length > 0) {
// 从上传的文件中加载 PDF 文件
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function () {
loadPdfFromData(new Uint8Array(reader.result));
};
reader.readAsArrayBuffer(file);
}
});
function loadPdfFromUrl(url) {
pdfjsLib
.getDocument(url)
.promise.then(function (pdf) {
// 获取PDF文件的所有页面
const pageNumbers = Array.from(
new Array(pdf.numPages),
(val, index) => index + 1
);
return Promise.all(
pageNumbers.map(function (num) {
return pdf.getPage(num);
})
);
})
.then(function (pages) {
// 渲染每一页到画布上
const canvases = pages.map(function (page) {
const viewport = page.getViewport({ scale: 1 });
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
return page
.render({
canvasContext: canvas.getContext("2d"),
viewport: viewport,
})
.promise.then(function () {
return canvas;
});
});
// 等待所有画布都准备好之后,将它们合并成一个大的画布
return Promise.all(canvases).then(function (screenshots) {
const combinedCanvas = document.createElement("canvas");
combinedCanvas.width = Math.max(
...screenshots.map((shot) => shot.width)
);
combinedCanvas.height = screenshots.reduce(
(sum, shot) => sum + shot.height,
0
);
let yPosition = 0;
screenshots.forEach(function (shot) {
combinedCanvas.getContext("2d").drawImage(shot, 0, yPosition);
yPosition += shot.height;
});
return combinedCanvas;
});
})
.then(function (combinedCanvas) {
// 保存为本地文件
const filename = "combined.png";
combinedCanvas.toBlob(function (blob) {
saveAs(blob, filename);
},0.88);
})
.catch(function (reason) {
console.error(`Failed to load PDF: ${reason}`);
});
}
function loadPdfFromData(data) {
pdfjsLib
.getDocument({ data: data })
.promise.then(function (pdf) {
// 获取PDF文件的所有页面
const pageNumbers = Array.from(
new Array(pdf.numPages),
(val, index) => index + 1
);
return Promise.all(
pageNumbers.map(function (num) {
return pdf.getPage(num);
})
);
})
.then(function (pages) {
// 渲染每一页到画布上
const canvases = pages.map(function (page) {
const viewport = page.getViewport({ scale: 1 });
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
return page
.render({
canvasContext: canvas.getContext("2d"),
viewport: viewport,
})
.promise.then(function () {
return canvas;
});
});
// 等待所有画布都准备好之后,将它们合并成一个大的画布
return Promise.all(canvases).then(function (screenshots) {
const combinedCanvas = document.createElement("canvas");
combinedCanvas.width = Math.max(
...screenshots.map((shot) => shot.width)
);
combinedCanvas.height = screenshots.reduce(
(sum, shot) => sum + shot.height,
0
);
let yPosition = 0;
screenshots.forEach(function (shot) {
combinedCanvas.getContext("2d").drawImage(shot, 0, yPosition);
yPosition += shot.height;
});
return combinedCanvas;
});
})
.then(function (combinedCanvas) {
// 保存为本地文件
const filename = "combined.png";
combinedCanvas.toBlob(function (blob) {
saveAs(blob, filename);
},0.88);
})
.catch(function (reason) {
console.error(`Failed to load PDF: ${reason}`);
});
}
</script>
</body>
</html>