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>
相关推荐
web打印社区4 小时前
2026最新Web静默打印解决方案,无插件无预览,完美替代Lodop
前端·javascript·vue.js·electron·pdf
其实防守也摸鱼8 小时前
带你了解与配置phpmyadmin
笔记·安全·网络安全·pdf·编辑器·工具·调试
sensor_WU9 小时前
【原创】PDF 加密、管控终极工具
pdf·pdf 加密·pdf 转 exe·pdf aes256·pdf 密码
AI刀刀11 小时前
手机AI怎么导出pdf
人工智能·ai·智能手机·pdf·deepseek·ds随心转
eastyuxiao12 小时前
OpenClaw 免费 PDF 技能组合 + 一键指令(零收费、无订阅)
pdf
eastyuxiao13 小时前
OpenClaw的PDF处理Skill收费吗?
人工智能·pdf
Tdsay_13 小时前
PDF 加水印怎么做?一次真实使用在线工具的体验分享(免费、本地处理)
pdf·pdf加水印·土豆丝在线工具
2501_9307077813 小时前
使用C#代码在PDF文件中添加图片水印
pdf
阳光Cherry梦13 小时前
下载利用pdfjs提供的viewer.html展示pdf文件
pdf
qq_4275398313 小时前
iframe 嵌入预览 PDF ,禁用右键菜单、打印下载按钮不展示
前端·javascript·vue.js·pdf