H5页面在线预览pdf

H5页面预览pdf

一般的做法是在浏览器中打开pdf文件,但是这种方式会导致浏览器的工具栏和地址栏也一起显示出来,影响用户体验。因此,我们需要在H5页面中实现一个预览pdf的功能,例如在网页或微信小程序中嵌入 PDF 文档,方便用户直接预览文件

一. 使用PDF.js 和 pdf.worker.js

pdf.jspdf.worker.js:PDF.js 的核心文件和 Worker 脚本文件。

有需要的可以从gitcode中获取

  1. HTML 和样式设计
    在 HTML 中,创建一个全屏的容器 pdf-container 用于展示 PDF 页面,CSS 通过 100vw 和 100vh 让容器适配整个屏幕。样式代码如下:

HTML 和样式设计

在 HTML 中,创建一个全屏的容器 pdf-container 用于展示 PDF 页面,并通过 CSS 设置其宽高为 100vw 和 100vh,确保容器充满屏幕。样式代码如下:

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>移动端 PDF 预览</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    .pdf_box, #pdf-container {
      width: 100vw;
      height: 100vh;
      overflow: scroll;
    }
    canvas {
      width: 100vw;
    }
  </style>
</head>
<body>
  <div id="pdf-container"></div>
</body>
</html>

操作js部分

html 复制代码
<script src="./js/pdf.js"></script>
<script>
  pdfjsLib.GlobalWorkerOptions.workerSrc = "./js/pdf.worker.js";

  const pdfUrl = "13409.pdf";
  const targetDom = "pdf-container";

  pdfjsLib.getDocument(pdfUrl).promise.then(async (doc) => {
    for (let pageNum = 1; pageNum <= doc.numPages; pageNum++) {
      await renderPage(doc, pageNum, targetDom);
    }
  });

  function renderPage(pdfDoc, pageNumber, containerId) {
    return new Promise((resolve) => {
      pdfDoc.getPage(pageNumber).then((page) => {
        const scale = 1;
        const viewport = page.getViewport({ scale });
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        document.getElementById(containerId).appendChild(canvas);

        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        };
        page.render(renderContext).promise.then(resolve);
      });
    });
  }
</script>
  1. 设置 Worker 路径:pdfjsLib.GlobalWorkerOptions.workerSrc 用于指定 pdf.worker.js的路径,提升加载效率。
  2. 加载 PDF 文件:pdfjsLib.getDocument(pdfUrl).promise 以异步方式加载 PDF 文件,返回 PDF 文档对象 doc。
  3. 遍历渲染每一页:通过 for 循环遍历文档的每一页,调用 renderPage 函数将页面内容渲染到 canvas 上,并插入到 pdf-container 中。
  4. 页面缩放和适配:page.getViewport({ scale }) 设置页面的缩放比例,从而控制页面的显示尺寸。
    其实就是把pdf通过canvas转换成图片生成出来,然后通过css设置成全屏,这样就可以实现pdf的预览了

存在的问题:图片显示模糊

由于 PDF.js 默认使用 1 倍的缩放比例,导致生成的图片在移动端显示模糊。为了解决这个问题,我们可以通过设置 scale 参数来调整缩放比例,使其适应移动端屏幕的分辨率。

javascript 复制代码
const scale = window.devicePixelRatio; // 获取设备的像素比

scale 参数设置为 window.devicePixelRatio,即可根据设备的像素比来调整缩放比例,从而提高图片的清晰度。

相关推荐
一只花里胡哨的程序猿9 分钟前
odoo打印pdf速度慢问题
pdf·odoo
烛阴14 分钟前
【TS 设计模式完全指南】从零到一:掌握TypeScript建造者模式,让你的对象构建链式优雅
javascript·设计模式·typescript
前端Hardy40 分钟前
HTML&CSS:有趣的漂流瓶
前端·javascript·css
前端Hardy42 分钟前
HTML&CSS :惊艳 UI 必备!卡片堆叠动画
前端·javascript·css
无羡仙1 小时前
替代 Object.freeze 的精准只读模式
前端·javascript
小菜全2 小时前
uniapp新增页面及跳转配置方法
开发语言·前端·javascript·vue.js·前端框架
白水清风2 小时前
关于Js和Ts中类(class)的知识
前端·javascript·面试
前端Hardy2 小时前
只用2行CSS实现响应式布局,比媒体查询更优雅的布局方案
javascript·css·html
灵海之森2 小时前
Python将md转html,转pdf
pdf
车口3 小时前
滚动加载更多内容的通用解决方案
javascript