javascript: Multi-page PDF in Canvas using PDFJS 5.1

javascript 复制代码
<!DOCTYPE html>
<html>
<head>
     <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="apple-moible-web-app-capable" content="yes">
<meta name="apple-moible-web-app-status-bar-style" content="black">  
    <title> Multi-page PDF in Canvas using PDFJS 5.1</title>
    <meta content="在党的群众路线教育实践活动工作会议上的讲话,涂聚文,Geovin Du,塗聚文,geovindu,捷为工作室" name="keywords">
<meta content="在党的群众路线教育实践活动工作会议上的讲话,涂聚文,Geovin Du,塗聚文,geovindu,捷为工作室" name="description">
    <meta http-equiv="X-UA-Compatible" content="chrome =1" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <link rel="shortcut icon" href="~/favicon.ico" type="image/x-icon" />
    <link rel="icon" href="/favicon.ico" />
    <link rel="bookmark" href="/favicon.ico" type="image/gif" />
<meta name="author" content="Geovin Du 涂聚文,塗聚文,geovindu">
        <style>
        #pdfContainer {
            width: 90vw; /* 初始宽度为视口宽度的 90% */
            height: 90vh; /* 初始高度为视口高度的 90% */
            border: 1px solid #ccc;
            overflow: auto; /* 当内容超出容器大小时显示滚动条 */
        }
    </style>
</head>
 
<body>
   
     
  <div>
            <button id="firstPageBtn">第一页</button>
            <button id="prevPageBtn">上一页</button>
            <span id="pageInfo"></span>
            <button id="nextPageBtn">下一页</button>
            <button id="lastPageBtn">最后一页</button>
            <button id="downloadBtn">下载文档</button>
            <label for="zoomSelect">放大比例:</label>
            <select id="zoomSelect">
                <option value="0.5">50%</option>
                <option value="0.75">75%</option>
                <option value="1" selected>100%</option>
                <option value="1.25">125%</option>
                <option value="1.5">150%</option>
                <option value="2">200%</option>
            </select>
        </div>
        <div id="pdfContainer">
            <div id="pdfPages"></div>
        </div>
     
        <script src="../build/pdf.mjs" type="module"></script>
        <script id="script" type="module">
            try {
                var pdfData = atob('JVBERi0xLxMwolJUVPRgo=');
                console.log(pdfData);
                pdfjsLib.GlobalWorkerOptions.workerSrc = '../build/pdf.worker.mjs';
                var loadingTask = pdfjsLib.getDocument({ data: pdfData });
                const pdfContainer = document.getElementById('pdfContainer');
 
                function adjustContainerSize() {
                    pdfContainer.style.width = '90vw';
                    pdfContainer.style.height = '90vh';
                }
 
                window.addEventListener('load', adjustContainerSize);
                window.addEventListener('resize', adjustContainerSize);
 
                loadingTask.promise.then(async (pdf) => {
                    const totalPages = pdf.numPages;
                    const pdfPagesDiv = document.getElementById('pdfPages');
                    const pageInfo = document.getElementById('pageInfo');
                    const firstPageBtn = document.getElementById('firstPageBtn');
                    const prevPageBtn = document.getElementById('prevPageBtn');
                    const nextPageBtn = document.getElementById('nextPageBtn');
                    const lastPageBtn = document.getElementById('lastPageBtn');
                    const zoomSelect = document.getElementById('zoomSelect');
                    const downloadBtn = document.getElementById('downloadBtn');
 
                    let currentPage = 1;
                    let currentZoom = 1;
                    const canvasList = [];
 
                    async function renderPage(pageNumber, zoom) {
                        const canvas = canvasList[pageNumber - 1];
                        const page = await pdf.getPage(pageNumber);
                        const viewport = page.getViewport({ scale: zoom });
                        const outputScale = window.devicePixelRatio || 1;
 
                        canvas.width = Math.floor(viewport.width * outputScale);
                        canvas.height = Math.floor(viewport.height * outputScale);
                        canvas.style.width = Math.floor(viewport.width) + "px";
                        canvas.style.height = Math.floor(viewport.height) + "px";
 
                        const transform = outputScale !== 1
                            ? [outputScale, 0, 0, outputScale, 0, 0]
                            : null;
 
                        const context = canvas.getContext('2d');
                        const renderContext = {
                            canvasContext: context,
                            transform,
                            viewport,
                        };
                        await page.render(renderContext).promise;
                    }
                    // 渲染每一页
                    for (let i = 1; i <= totalPages; i++) {
                        const canvas = document.createElement('canvas');
                        canvas.style.border = '1px solid black';
                        canvas.style.display = 'none';
                        pdfPagesDiv.appendChild(canvas);
                        canvasList.push(canvas);
                    }
 
                    if (canvasList.length > 0) {
                        canvasList[0].style.display = 'block';
                        await renderPage(1, currentZoom);
                    }
                    //更新页码信息
                    function updatePageInfo() {
                        pageInfo.textContent = `第 ${currentPage} 页,共 ${totalPages} 页`;
                    }
                    updatePageInfo();
                    //第一页
                    firstPageBtn.addEventListener('click', (event) => {
                         
                        if (currentPage !== 1) {
                            canvasList[currentPage - 1].style.display = 'none';
                            currentPage = 1;
                            canvasList[currentPage - 1].style.display = 'block';
                            renderPage(currentPage, currentZoom);
                            updatePageInfo();
                        }
                    });
                    //上一页
                    prevPageBtn.addEventListener('click', (event) => {
                         
                        if (currentPage > 1) {
                            canvasList[currentPage - 1].style.display = 'none';
                            currentPage--;
                            canvasList[currentPage - 1].style.display = 'block';
                            renderPage(currentPage, currentZoom);
                            updatePageInfo();
                        }
                    });
                    //下一页
                    nextPageBtn.addEventListener('click', (event) => {
                        
                        if (currentPage < totalPages) {
                            canvasList[currentPage - 1].style.display = 'none';
                            currentPage++;
                            canvasList[currentPage - 1].style.display = 'block';
                            renderPage(currentPage, currentZoom);
                            updatePageInfo();
                        }
                    });
 
                    // 最后一页
                    lastPageBtn.addEventListener('click', (event) => {
                        
                        if (currentPage !== totalPages) {
                            canvasList[currentPage - 1].style.display = 'none';
                            currentPage = totalPages;
                            canvasList[currentPage - 1].style.display = 'block';
                            renderPage(currentPage, currentZoom);
                            updatePageInfo();
                        }
                    });
                    //放大缩小
                    zoomSelect.addEventListener('change', async () => {
                        currentZoom = parseFloat(zoomSelect.value);
                        await renderPage(currentPage, currentZoom);
                    });
 
                    //下载文档
                    downloadBtn.addEventListener('click', () => {
                        const binaryData = [];
                        binaryData.push(pdfData);
                        const blob = new Blob(binaryData, { type: 'application/pdf' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'geovindu.pdf';
                        a.click();
                        URL.revokeObjectURL(url);
                    });
 
                }).catch((error) => {
                    console.error('PDF 加载或渲染出错:', error);
                });
            } catch (error) {
                console.error('代码执行出错:', error);
            }
        </script>
         
</body>
</html>
相关推荐
程序员小杰@1 小时前
✨WordToCard使用分享✨
前端·人工智能·开源·云计算
larntin20021 小时前
vue2开发者sass预处理注意
前端·css·sass
Enti7c2 小时前
利用jQuery 实现多选标签下拉框,提升表单交互体验
前端·交互·jquery
SHUIPING_YANG2 小时前
在Fiddler中添加自定义HTTP方法列并高亮显示
前端·http·fiddler
互联网搬砖老肖3 小时前
Web 架构之前后端分离
前端·架构
水银嘻嘻3 小时前
web 自动化之 selenium+webdriver 环境搭建及原理讲解
前端·selenium·自动化
寧笙(Lycode)3 小时前
为什么使用Less替代原始CSS?
前端·css·less
-Camellia007-3 小时前
TypeScript学习案例(1)——贪吃蛇
javascript·学习·typescript
m0_zj3 小时前
57.[前端开发-前端工程化]Day04-webpack插件模式-搭建本地服务器
前端·webpack·node.js
GoFly开发者4 小时前
GoFly企业版框架升级2.6.6版本说明(框架在2025-05-06发布了)
前端·javascript·vue.js