如何快速的用pdfjs建立一个网页可以在线阅读你的PDF文件

#如何快速的用pdfjs建立一个网页可以在线阅读你的PDF文件#

也许很多人都用过这个pdfjs,我之前也用过,但是每次配置也是挺麻烦的,于是就写了一个页面远程调用CDN文件,这样一个页面就可以搞定,话不多说直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF Viewer</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    <style>
        #pdf-container {
            width: 100%;
            height: 100vh;
            overflow: auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            touch-action: pan-y pinch-zoom;
            position: relative;
        }
        #pdf-viewer {
            margin: 20px 0;
            max-width: 100%;
            height: auto;
        }
        #controls {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(255, 255, 255, 0.95);
            padding: 15px;
            border-radius: 15px 15px 0 0;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            align-items: center;
            z-index: 1000;
        }
        button {
            padding: 8px 20px;
            cursor: pointer;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            min-width: 44px;
            min-height: 44px;
            touch-action: manipulation;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        #page-info {
            margin: 0 10px;
            font-size: 16px;
        }
        #loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid #f3f3f3;
            border-top: 5px solid #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        .loading-text {
            font-size: 18px;
            color: #333;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        @media (max-width: 600px) {
            #controls {
                padding: 10px;
                gap: 5px;
            }
            button {
                padding: 8px 15px;
                font-size: 14px;
            }
            #page-info {
                font-size: 14px;
                width: 100%;
                text-align: center;
                order: -1;
            }
        }
    </style>
</head>
<body>
    <div id="pdf-container">
        <canvas id="pdf-viewer"></canvas>
        <div id="controls">
            <button id="prev-page" disabled>Previous</button>
            <span id="page-info">Page 1 of 1</span>
            <button id="next-page" disabled>Next</button>
            <button id="zoom-out">Zoom Out</button>
            <button id="zoom-in">Zoom In</button>
        </div>
        <div id="loading-overlay">
            <div class="loading-spinner"></div>
            <div class="loading-text">Loading PDF file...</div>
        </div>
    </div>

    <script>
        // 配置 PDF.js worker
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

        let currentPage = 1;
        let currentScale = 1.5;
        let pdfDoc = null;

        // 更新页面信息
        const updatePageInfo = () => {
            document.getElementById('page-info').textContent = `Page ${currentPage} of ${pdfDoc.numPages}`;
            document.getElementById('prev-page').disabled = currentPage <= 1;
            document.getElementById('next-page').disabled = currentPage >= pdfDoc.numPages;
        };

        // 渲染当前页面
        const renderPage = async () => {
            const page = await pdfDoc.getPage(currentPage);
            const canvas = document.getElementById('pdf-viewer');
            const context = canvas.getContext('2d');

            const viewport = page.getViewport({ scale: currentScale });
            canvas.height = viewport.height;
            canvas.width = viewport.width;

            const renderContext = {
                canvasContext: context,
                viewport: viewport
            };
            await page.render(renderContext);
            updatePageInfo();
        };

        // 加载PDF文件
        const loadPDF = async () => {
            const loadingOverlay = document.getElementById('loading-overlay');
            try {
                const loadingTask = pdfjsLib.getDocument('file/file.pdf');
                loadingTask.onProgress = function(progress) {
                    const percent = (progress.loaded / progress.total * 100).toFixed(0);
                    document.querySelector('.loading-text').textContent = `Loading PDF file... ${percent}%`;
                };
                pdfDoc = await loadingTask.promise;
                await renderPage();
                loadingOverlay.style.display = 'none';

                // 绑定按钮事件
                document.getElementById('prev-page').onclick = async () => {
                    if (currentPage > 1) {
                        currentPage--;
                        await renderPage();
                    }
                };

                document.getElementById('next-page').onclick = async () => {
                    if (currentPage < pdfDoc.numPages) {
                        currentPage++;
                        await renderPage();
                    }
                };

                document.getElementById('zoom-in').onclick = async () => {
                    currentScale += 0.25;
                    await renderPage();
                };

                document.getElementById('zoom-out').onclick = async () => {
                    if (currentScale > 0.5) {
                        currentScale -= 0.25;
                        await renderPage();
                    }
                };
            } catch (error) {
                console.error('Error loading PDF:', error);
                loadingOverlay.querySelector('.loading-text').textContent = 'Failed to load PDF file. Please ensure the file exists and is accessible.';
                loadingOverlay.querySelector('.loading-spinner').style.display = 'none';
            }
        };

        // 页面加载完成后执行
        window.onload = loadPDF;
    </script>
</body>
</html>

页面js和css都写好了,当这个文件很大,需要加载一些时间的时候页面也会出现加载的进度条。

喜欢的拿去直接用吧。

相关推荐
oh,huoyuyan2 小时前
火语言RPA--切割PDF文档
pdf·rpa
火星技术18 小时前
免费pdf格式转换工具
pdf
开开心心就好1 天前
高效玩转 PDF:实用的分割、合并操作详解
android·java·网络·windows·智能手机·pdf·软件工程
oh,huoyuyan1 天前
火语言RPA--PDF提取文本
pdf·rpa
oh,huoyuyan2 天前
火语言RPA--PDF提取表格
pdf·rpa
GIS小小研究僧2 天前
Stiring-PDF:开源免费的PDF文件处理软件
pdf
软件工程小施同学2 天前
【最新区块链论文录用资讯】CCF A—NDSS 2025 (一) 附pdf下载
pdf·区块链
Ylsh37022 天前
PDF加盖骑缝章 ,还是第一次见
pdf·github·开源协议·wps