html展示pdf

本文以html + js为例,需自行下载pdfjs-dist插件 npm i pdfjs-dist@2.11.338

pdfjs-dist - npm

PDF.js - Examples

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用教程</title>
</head>
<body>

<div class="detail">
    <div id="pdf-container" style="width: 600px; height: 500px;"></div>
</div>
</body>
</html>

<script src="/js/pdfjs-dist/build/pdf.js"></script>


<script>
// xx.html?name=demo.pdf
    /* 获取地址栏中传递的字段 */
    function getQueryVariable(variable) {
        const query = window.location.search.substring(1);
        const vars = query.split('&');
        for (let i = 0; i < vars.length; i++) {
            const pair = vars[i].split('=');
            if (decodeURIComponent(pair[0]) === variable) {
                return decodeURIComponent(pair[1]);
            }
        }
        return null;
    }
    // 获取传递的 name 属性值
    let url = getQueryVariable('name');
    // 如果没有通过查询参数传递,尝试从 URL 的 hash 部分获取
    if (!url) {
        url = window.location.hash.slice(1);
    }
    // 如果仍然没有获取到,使用默认值或提示错误
    if (!url) {
        console.error('PDF URL not found.');
    }


// 直接从这里CV就行
   let resUrl = `/tutorial/${url}`
    pdfjsLib.getDocument(resUrl).promise.then(function (pdf) {
        const numPages = pdf.numPages;
        const container = document.getElementById('pdf-container');

        for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
            pdf.getPage(pageNumber).then(function (page) {
                const scale = 1.5;
                const viewport = page.getViewport({scale: scale});

                const canvas = document.createElement('canvas');
                canvas.className = 'pdf-page';
                canvas.width = viewport.width;
                canvas.height = viewport.height;

                const context = canvas.getContext('2d');
                const renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };

                page.render(renderContext);
                container.appendChild(canvas);
            });
        }
    }).catch(function (error) {
        console.error('Error loading PDF:', error);
    });
</script>


<style>
    .detail {
        width: calc(100vw - 40px);
        height: 100vh;
        position: relative;
    }
</style>
相关推荐
开开心心_Every10 小时前
限时免费加密、隐藏、锁定文件文件夹好工具
运维·服务器·人工智能·edge·pdf·逻辑回归·深度优先
不知名的老吴11 小时前
PDF神器-PDF Candy v2.89全能PDF工具箱便携版
pdf
其实秋天的枫15 小时前
2026年新大纲普通话考试真题题库50套【PDF电子版】
经验分享·pdf
PieroPc16 小时前
用tkinter 做一个通过 扫描仪硬件 扫描纸质文档的软件 支持pdf
python·pdf·扫描
优化控制仿真模型21 小时前
【26年最新】新大纲普通话考试真题题库50套~PDF电子版
经验分享·pdf
优化控制仿真模型2 天前
【2026年6月最新】英语四级历年真题及答案解析PDF电子版(2015-2025年12月)
经验分享·pdf
开开心心就好2 天前
进程启动瞬间暂停工具,适合调试多开
linux·运维·安全·pdf·智能音箱·智能手表·1024程序员节
yivifu3 天前
完美的PyMuPDF删除pdf页面文字水印
python·pdf·pymupdf·去水印
weixin_441003643 天前
廖华英《中国文化概况》修订版+批注版+译文版+笔记+课件PPT+配套题库 PDF
笔记·pdf·中国文化概况
Source.Liu3 天前
【office2pdf】office2pdf 纯 Rust 实现的 Office 转 PDF 库
rust·pdf·office2pdf