pdf.js滚动翻页的例子
可以使用 pdf.js
创建一个简单的滚动翻页效果。以下是一个基本示例,展示如何实现:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>PDF.js Scroll Example</title><script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js"></script><style>#canvasContainer {overflow-y: auto;height: 100vh;}canvas {display: block;margin: 20px auto;}</style>
</head>
<body><div id="canvasContainer"></div><script>const url = 'path/to/your.pdf'; // 替换为你的PDF文件路径const canvasContainer = document.getElementById('canvasContainer');const loadingTask = pdfjsLib.getDocument(url);loadingTask.promise.then(pdf => {const renderPage = (num) => {pdf.getPage(num).then(page => {const viewport = page.getViewport({ scale: 1 });const canvas = document.createElement('canvas');const context = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;const renderContext = {canvasContext: context,viewport: viewport,};page.render(renderContext).promise.then(() => {canvasContainer.appendChild(canvas);});});};for (let i = 1; i <= pdf.numPages; i++) {renderPage(i);}}).catch(console.error);</script>
</body>
</html>
说明:
- 替换路径:将
path/to/your.pdf
替换为你的PDF文件路径。 - 样式:
canvasContainer
使用overflow-y: auto;
以实现垂直滚动。 - 渲染页面:通过循环加载和渲染所有页面。
这样,当你向下滚动时,所有页面都将加载并展示。