<!DOCTYPE html>
<html>
<head>
    <title>PDF.js Example</title>
    <style>
        #pdf-container {
            width: 800px;
            height: 600px;
        }
    </style>
</head>
<body>
<div id="pdf-container"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.js"></script>
<script>
    // 指定工作线程脚本的路径
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.worker.js';

    // 获取容器元素
    var container = document.getElementById('pdf-container');

    // 加载PDF文档
    pdfjsLib.getDocument('./2.pdf').promise.then(function(pdf) {
        // 获取第一页
        pdf.getPage(1).then(function(page) {
            var scale = 1.5;
            var viewport = page.getViewport({ scale: scale });

            // 创建一个<canvas>元素用于显示PDF页面
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            canvas.width = viewport.width;
            canvas.height = viewport.height;

            // 将PDF页面渲染到<canvas>元素中
            page.render({
                canvasContext: context,
                viewport: viewport
            });

            // 将<canvas>元素添加到容器中
            container.appendChild(canvas);
        });
    });
</script>
</body>
</html>

添加翻页功能

var currentPage = 1;
function renderPage(pageNumber) {
  container.innerHTML = ''; // 清空容器
  pdf.getPage(pageNumber).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport({ scale: scale });
    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    page.render({
      canvasContext: context,
      viewport: viewport
    });
    container.appendChild(canvas);
    currentPage = pageNumber;
  });
}

// 监听翻页按钮点击事件
document.getElementById('prev-btn').addEventListener('click', function() {
  if (currentPage > 1) {
    renderPage(currentPage - 1);
  }
});

document.getElementById('next-btn').addEventListener('click', function() {
  if (currentPage < pdf.numPages) {
    renderPage(currentPage + 1);
  }
});
 

GitHub 加速计划 / pd / pdf.js
47.48 K
9.86 K
下载
PDF Reader in JavaScript
最近提交(Master分支:3 个月前 )
18284815 [Editor] Update the disclaimer string in the new alt-text dialog (bug 1911738) 3 个月前
fc602c65 And tweak the css in order to take into account that disclaimer can be on two (or more lines). 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐