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>
相关推荐
阿幸软件杂货间2 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
reembarkation2 天前
使用pdfjs-dist 预览pdf,并添加文本层的实现
前端·javascript·pdf
reembarkation2 天前
vue-pdf 实现blob数据的预览
javascript·vue.js·pdf
Light603 天前
领码方案|Linux 下 PLT → PDF 转换服务超级完整版:异步、权限、进度(一气呵成)
linux·spring boot·pdf·gpcl6/ghostpcl·s3/oss·权限与审计·异步与进度
伟贤AI之路3 天前
【分享】中小学教材课本 PDF 资源获取指南
人工智能·pdf
东风西巷3 天前
PDFgear:免费全能的PDF处理工具
前端·pdf·软件需求
Sunny_yiyi4 天前
Java根据模版导出PDF文件
java·开发语言·pdf
小*-^-*九4 天前
php 使用html 生成pdf word wkhtmltopdf 系列2
pdf·html·php
千册4 天前
pyside6 的pdf显示测试 -- 01
开发语言·python·pdf
qq_172805594 天前
Go 语言 PDF 生成库综合比较与实践指南
开发语言·golang·pdf