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>
相关推荐
百事牛科技4 天前
保护文档安全:PDF限制功能详解与实操
windows·pdf
开开心心就好4 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
Felicia-侧听5 天前
如何统一PDF页面宽度?统一pdf宽度的2种方法
pdf·pdf宽度统一
开开心心_Every5 天前
音频格式互转工具,支持Mp3ApeWavFlac互转
linux·运维·服务器·typescript·edge·pdf·asp.net
2501_930707785 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
悟乙己5 天前
实施手册:如何自己构建财务PDF文件内容抽取引擎
pdf
xin_yao_xin5 天前
PDF 转 图片(python)
python·pdf
汤姆百宝箱6 天前
2026新版教材电子课本1-9年级新教材PDF(完整电子版下载)
pdf·小学课本·初中课本·电子教材·电子课本·2026新教材·2026新课本
开开心心就好6 天前
内存清理软件灵活设置,自动阈值快捷键清
运维·服务器·windows·pdf·harmonyos·risc-v·1024程序员节
海兰6 天前
【接上篇】多格式文档支持扩展方案(PDF_Word_Excel)
pdf·word·excel