前端展示 PDF 预览的几种方法

一、js实现pdf预览

1. iframe 标签

HTML 内联框架元素 iframe 表示嵌套的 browsing context。它能够将另一个 HTML 页面嵌入到当前页面中。

<iframe src="./test.pdf" height="900px;" width="800px"></iframe>

2. embed 标签

HTML embed 元素将外部内容嵌入文档中的指定位置。此内容由外部应用程序或其他交互式内容源(如浏览器插件)提供

<embed src="./test.pdf" type="application/pdf" width="100%" height="100%" />

3. object 标签

HTML object 元素(或者称作 HTML 嵌入对象元素)表示引入一个外部资源,这个资源可能是一张图片,一个嵌入的浏览上下文,亦或是一个插件所使用的资源。

<object
  data="./test.pdf"
  type="application/pdf"
  width="100%"
  height="100%"
></object>

注意:以上三种自带toolbar栏,并且每个浏览器不一致,如下图:
在这里插入图片描述
去掉方法:

<iframe
 src=test.pdf#toolbar=0"  //pdf地址后添加#toolbar=0
 type="application/x-google-chrome-pdf"    
 width="100%"
 height="100%"></iframe> 

下载pdf方法:(相同域名直接下载到本地,域名不同会在新页面打开)

download("test.pdf","文件名")

function download (url, name) {
    
    
    const aLink = document.createElement('a')
     aLink.download = name
     aLink.href = url
     aLink.dispatchEvent(new MouseEvent('click', {
    
    }))
 }

4. 使用 PDF.js 插件

二、微信小程序pdf文件的三种展示方式

1. pdfjs第三方

<web-view src="https://byfile.disscode.cn/pdfjs-2.8/web/viewer.html?file={
    
    {url}}"></web-view>

2. markdown第三方

<web-view src="https://byfile.disscode.cn/marked/marked.html?file={
    
    {url}}"></web-view>

3. 微信小程序自带方式

通过wx.downloadFile下载pdf文件,再通过wx.openDocument展示。

 wx.downloadFile({
    
    
     url: 你的pdf地址,//可以是后台传过来的路径
     success: function(res) {
    
    
         const filePath = res.tempFilePath
         wx.openDocument({
    
    
             filePath: filePath,
             showMenu: "true",
             fileType: "pdf",
             success: function(res) {
    
    
                 //成功
             }
         })
     }
 })

模拟器上会直接下载到本地,真机调试可以实现预览,并且安卓上点击右上角可以直接下载到本地,在最近文件中可以找到。注意:苹果右上角无直接下载

猜你喜欢

转载自blog.csdn.net/qq_44749901/article/details/128197034