如何使用PDF.js完整显示PDF文档而非仅单页?
解决PDF.js仅显示第一页的问题
要实现完整显示PDF所有页面,核心是在加载文档后遍历所有页码,逐一渲染每一页到独立的canvas元素中。以下是针对你的代码的修改方案:
1. 修改script.js代码
原代码仅处理了第一页,需添加循环逻辑渲染所有页面:
// 初始化PDF.js Worker路径 pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.js'; // 渲染PDF函数 function renderPDF(url) { pdfjsLib.getDocument(url).promise.then(function(pdf) { const totalPages = pdf.numPages; const container = document.getElementById('pdf-container'); // 遍历所有页码,逐一渲染 for (let pageNum = 1; pageNum <= totalPages; pageNum++) { pdf.getPage(pageNum).then(function(page) { const scale = 1.5; const viewport = page.getViewport({ scale: scale }); // 为当前页创建独立canvas const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); canvas.height = viewport.height; canvas.width = viewport.width; // 将canvas加入页面容器 container.appendChild(canvas); // 渲染当前页到canvas const renderContext = { canvasContext: context, viewport: viewport }; page.render(renderContext); }); } }).catch(function(error) { console.error('PDF加载失败:', error); }); } // 调用渲染函数,替换为你的PDF文件路径 renderPDF('your-pdf-file.pdf');
2. 调整index.php结构
确保页面包含用于承载所有PDF页面的容器:
<!DOCTYPE html> <html> <head> <title>PDF完整预览</title> <link rel="stylesheet" href="css.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script> </head> <body> <div id="pdf-container"></div> <script src="script.js"></script> </body> </html>
3. 优化css.css样式
添加基础样式提升页面排版体验:
#pdf-container { display: flex; flex-direction: column; align-items: center; padding: 20px; gap: 20px; } #pdf-container canvas { box-shadow: 0 0 10px rgba(0,0,0,0.1); max-width: 100%; height: auto; }
关键修改说明
- 通过
pdf.numPages获取总页数,循环遍历所有页码 - 为每一页创建独立的canvas元素,避免覆盖第一页的渲染结果
- 将每个渲染完成的canvas添加到页面容器,实现分页展示
内容的提问来源于stack exchange,提问作者gagaltotal666
相关产品推荐
相关产品推荐

