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>
相关推荐
Java面试题总结1 小时前
基于 Java 的 PDF 文本水印实现方案(iText7 示例)
java·python·pdf
傻啦嘿哟3 小时前
Python操作PDF页面详解:删除指定页的完整方案
开发语言·python·pdf
m5655bj11 小时前
使用 C# 修改 PDF 页面尺寸
java·pdf·c#
geovindu12 小时前
python: 简单提取PDF文档内文字
开发语言·python·pdf
m0_6948455712 小时前
HandBrake 是什么?视频转码工具使用与服务器部署教程
服务器·前端·pdf·开源·github·音视频
yivifu1 天前
使用PyMuPdf删除PDF文档中的水印
pdf·pymupdf·去水印
ComPDFKit1 天前
ComPDF的产品升级:从工具包到PDF服务
pdf
占疏1 天前
pdf文件解析
pdf
开开心心_Every1 天前
音频视频转文字工具,离线语音识别免费
人工智能·游戏·微信·pdf·excel·语音识别·memcache
开开心心_Every1 天前
电脑网速加速工具,无线有线叠加网络
网络·游戏·微信·pdf·电脑·excel·语音识别