如何快速的用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都写好了,当这个文件很大,需要加载一些时间的时候页面也会出现加载的进度条。

喜欢的拿去直接用吧。

相关推荐
m0_5405077818 小时前
2026考研数学张宇武忠祥复习视频课,高数基础班+讲义PDF
考研·pdf
ElasticPDF-新国产PDF编辑器2 天前
Vue 项目 PDF 批注插件库在线版 API 示例教程
前端·vue.js·pdf
ElasticPDF-新国产PDF编辑器2 天前
Vue PDF Annotation plugin library online API examples
javascript·vue.js·pdf
Eiceblue2 天前
.NET用C#在PDF文档中添加、删除和替换图片
开发语言·pdf·c#·.net·idea
开开心心就好2 天前
解决 PDF 难题:批量处理、文档清理与自由拆分合并
java·学习·eclipse·pdf·word·excel·生活
ElasticPDF-新国产PDF编辑器2 天前
Vue 项目使用 pdf.js 及 Elasticpdf 教程
javascript·vue.js·pdf
hello_simon2 天前
PDF转换:在线将PDF转PPT并且可编辑文字图片,超快速转换软件,无需下载
pdf·html·excel·pdf转html·excel转pdf格式
ElasticPDF-新国产PDF编辑器2 天前
HTML && jQuery PDF Annotation plugin library free online API examples
pdf·html·jquery
inxunoffice2 天前
批量将 Markdown 转换为 Word/PDF 等其它格式
pdf·word
iReachers2 天前
PDF转安卓APP软件, 支持加密添加一机一码, 静态密码, 保护APK版权使用说明和CSDN文库下载
android·pdf·pdf加密·pdf转app·pdf转apk·一机一码加密