吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 5094|回复: 9
收起左侧

[其他转载] vue3中使用pdfjs-dist预览pdf

 关闭 [复制链接]
安云 发表于 2021-3-15 12:17
本帖最后由 安云 于 2021-3-16 09:07 编辑







[md]# vue 预览pdf

### 推荐几款觉得不错得预览pdf插件

[pdf.js](http://mozilla.github.io/pdf.js/)

[pdfdist-pdf](https://github.com/mozilla/pdfjs-dist)

[vue-pdf](https://github.com/FranckFreiburger/vue-pdf)

vue-pdf 感觉使用是最简单的,本文主要是介绍vue3.0中预览pdf,但是由于vue-pdf 在vue3.0中不支持,所以就不说明了。
vue2.0推荐大家使用vue-pdf

话不多说,马上上主菜

#### 一丶安装
```
npm install pdfjs-dist@2.5.207
```

@后面加版本号,npm程序会下载固定版本的包。为啥要用这个版本,因vue-3.0中使用过高或者过低的版本,会报错。
因本人工作进度,也没详细去了解

####  二丶封装pdfjs-dist

    找到node-modules>pdfjs-dist>es5文件夹
    复制文件夹里面文件到public>static>pdf(新建pdf文件夹)

  1.新建components>pdf>pdf.js (主要是对pdf封装)
   
                import getPdfjsDist from './getPdfjsDist'

                export default {
                                 name: 'Pdf',
                                        props: {
                                        url: {
                                                        type: String,
                                                        default: ''
                                        },
                                        type: {
                                                        type: String,
                                                        default: 'canvas'
                                        },
                                        pdfjsDistPath: {
                                                        type: String,
                                                        default: '.'
                                        }
                        },
                        data() {
                                        return {
                                                        pdfViewer: null,
                                                        pdfLinkService: null,
                                                        currentScale: 'page-width',
                                                        loadingTask: null
                                        }
                        },

                        methods: {
                                        onPagesInit({ source }) {
                                                        source.currentScaleValue = this.currentScale
                                        },
                                        async pdfLibInit() {
                                                        let pdfjsLib = window.pdfjsLib;
                                                        let pdfjsViewer = window.pdfjsViewer
                                                        if (!pdfjsLib || !pdfjsViewer) {
                                                                        try {
                                                                                        await getPdfjsDist(this.pdfjsDistPath)
                                                                                        this.CMAP_URL = `${this.pdfjsDistPath}/pdf/cmaps/`;
                                                                                        console.log( this.CMAP_URL)
                                                                                        pdfjsLib = window.pdfjsLib;
                                                                                        pdfjsLib.GlobalWorkerOptions.workerSrc = `${this.pdfjsDistPath}/pdf/build/pdf.worker.js`
                                                                                        pdfjsViewer = window.pdfjsViewer
                                                                        } catch (error) {
                                                                                        // console.log(error)
                                                                                        // pdfjs文件获取失败
                                                                                        return
                                                                        }
                                                        }

                                                        const container = this.$refs.container
                                                        const eventBus = new pdfjsViewer.EventBus();

                                                        // (Optionally) enable hyperlinks within PDF files.
                                                        const pdfLinkService = new pdfjsViewer.PDFLinkService({
                                                                        eventBus: eventBus,
                                                        });
                                                        this.pdfLinkService = pdfLinkService
                                                        const pdfViewer = new pdfjsViewer.PDFViewer({
                                                                        container: container,
                                                                        eventBus: eventBus,
                                                                        linkService: pdfLinkService,
                                                                        renderer: this.type,
                                                                        textLayerMode: 0,
                                                                        downloadManager: new pdfjsViewer.DownloadManager({}),
                                                                        enableWebGL: true
                                                        });
                                                        this.pdfViewer = pdfViewer
                                                        pdfLinkService.setViewer(pdfViewer);

                                                        eventBus.on("pagesinit", this.onPagesInit);
                                        },
                                        renderPdf() {
                                                        if (!this.url) { return }
                                                        // Loading document.
                                                        if (this.pdfViewer === null || this.pdfLinkService === null) {
                                                                        return
                                                        }
                                                        if (this.loadingTask !== null) {
                                                                        this.loadingTask.destroy()
                                                                        this.loadingTask = null
                                                        }
                                                        this.loadingTask = window.pdfjsLib.getDocument({
                                                                        cMapUrl: this.CMAP_URL,
                                                                        cMapPacked: true,
                                                                        url: this.url,
                                                        });
                                                        return this.loadingTask.promise.then((pdfDocument) => {
                                                                        if (pdfDocument.loadingTask.destroyed || !this.url) { return }
                                                                        this.pdfViewer.setDocument(pdfDocument)
                                                                        this.pdfLinkService.setDocument(pdfDocument, null);
                                                                        this.loadingTask = null
                                                        }).catch(error => {
                                                                        console.log(error)
                                                        });
                                        }
                        },
                        mounted() {
                                        this.pdfLibInit().then(() => {
                                                        this.renderPdf()
                                        })
                        },
                        watch: {
                                        url() {
                                                        // 如果存在pdfViewer则取消渲染
                                                        if (this.pdfViewer) {
                                                                        this.pdfViewer._cancelRendering()
                                                        }
                                                        this.renderPdf()
                                        }
                        },
                        render() {
                                        return (
                                                        <div class="pdf-view">
                                                                        <div id="viewerContainer" ref="container">
                                                                                        <div id="viewer" class="pdfViewer" />
                                                                        </div>
                                                        </div>
                                        )
                        }
        }
        
   
  2 新建components>pdf>getPdfjsDist(获取文件)
    ```
                const getJavsScript = (src) => {
                                return new Promise((resolve, reject) => {
                                        const script = document.createElement('script')
                                        script.onload = resolve
                                        script.onerror = reject

                                        script.src = src
                                        document.body.append(script)
                                })
                        }
                        const getCss = (href) => {
                                return new Promise((resolve, reject) => {
                                        const link = document.createElement('link')

                                        link.onload = resolve
                                        link.onerror = reject

                                        link.setAttribute('rel', 'stylesheet')
                                        link.setAttribute('type', 'text/css')
                                        link.href=href
                                        document.body.append(link)
                                })
                        }
                        const getPdfjsDist = (pdfjsDistPath) => {
                                return getJavsScript(`${pdfjsDistPath}/pdf/build/pdf.js`)
                                .then(() => {
                                        return Promise.all([
                                                getJavsScript(`${pdfjsDistPath}/pdf/web/pdf_viewer.js`),
                                                getCss(`${pdfjsDistPath}/pdf/web/pdf_viewer.css`)
                                        ])
                                })
                        }
                        export default getPdfjsDist
                        


####  三丶页面使用

```
<template>
    <div style="width:100%;overflow:hidden;padding-top:50px">
      <!-- canvas渲染方式 -->
      <pdf :url="pdfUrl" :type="'canvas'" :pdfjsDistPath="'/static'" />
    </div>
  </div>
</template>
import pdf from "@/components/PDF/pdf";
export default {
  components: {
    pdf
  },
  data() {
    return {
      pdfUrl: "",
    };
  },
  created() {
    this.pdfUrl = this.$route.query.src;
  }
```
备注:
关于印章不显示的问题

public>static>pdf>build>pdf.worker.js

if (data.fieldType === "Sig") {
      data.fieldValue = null;
                        // 注释下面这句话
      // _this3.setFlags(_util.AnnotationFlag.HIDDEN);
}
```
蓝奏云 下载:https://wws.lanzouj.com/i4tWEmzdqij 密码:3v70

PDF.rar

1.57 KB, 下载次数: 64, 下载积分: 吾爱币 -1 CB

组件附件

免费评分

参与人数 2吾爱币 +2 热心值 +2 收起 理由
退役单身 + 1 + 1 用心讨论,共获提升!
alexj + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

bhbhxy 发表于 2021-3-15 13:56
感谢楼主分享优质代码
RagnarokRay 发表于 2021-3-15 14:07
fengyue 发表于 2021-3-15 14:15
alexj 发表于 2021-3-15 14:45
这种文章都是应该感谢的。
ss_wlc 发表于 2021-3-21 08:49
感谢分享,先收藏,正好再学vue。
dxxbjl 发表于 2022-2-25 12:48
非常感谢,大佬有没有分页的代码
 楼主| 安云 发表于 2022-2-28 14:42
dxxbjl 发表于 2022-2-25 12:48
非常感谢,大佬有没有分页的代码

分页的话,你有element框架里面的组件就行,我的分页可能不太合适你
dxxbjl 发表于 2022-4-1 10:31
写了个假分页,终结!
dxxbjl 发表于 2022-5-16 09:02
嘟嘟嘟嘟嘟嘟
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-28 11:34

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表