码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • vue3 实现pdf预览


    需要下载pdfjs-dist

    <template>
        <a-modal class="fill-modal" v-model:open="state.visible" :title="state.modalTitle" width="50%" @cancel="handleCancel">
            <div class="preview-btns-posi">
                <a-button type="primary" @click="exportBtn" :loading="state.downLoading">下载</a-button>
                <a-button @click="handleCancel" type="primary">返回</a-button>
            </div>
            <div class="interviewVideo_main" id="videoContainer">
                <!--此处根据pdf的页数动态生成相应数量的canvas画布-->
                <canvas v-show="state.show" v-for="pageIndex in pdfPages" :id="`pdf-canvas-` + pageIndex" :key="pageIndex"
                    style="display: block;width:100%;" class="canvas"></canvas>
            </div>
            <template #footer></template>
        </a-modal>
    </template>
    <script lang="ts" setup>
    import { ref, reactive, nextTick } from "vue";
    import * as pdfjsLib from "pdfjs-dist/build/pdf.js";
    
    import * as workerSrc from 'pdfjs-dist/build/pdf.worker.min.js'
    import { message } from "ant-design-vue";
    import { downloadBlobAsync } from "@/lib/tool";
    
    
    let pdfPages = ref(0); // pdf文件的页数
    let pdfDoc: any = reactive({})
    let pdfScale = ref(1.0); // 缩放比例
    const state: any = reactive({
        visible: false,
        downLoading: false,
        modalTitle: '预览文件',
        show: false
    })
    const props = defineProps<{
        file: {
            previewPath: string,
            originalFileName: string,
            path: string,
        }
    }>()
    
    //调用loadFile方法
    //获取pdf文档流与pdf文件的页数
    const loadFile = async (url: string) => {
        try {
            pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
            const loadingTask = pdfjsLib.getDocument(url);
            loadingTask.promise.then((pdf: any) => {
                state.show = true;
                pdfDoc = pdf;
                pdfPages.value = pdf.numPages;
                nextTick(() => {
                    renderPage(1);
                });
            }).catch((err: any) => {
                console.error(err);
                pdfDoc = null
                state.show = false
            });
        } catch (error) {
            console.error(error)
        }
    };
    //渲染pdf文件
    const renderPage = (num: number) => {
        pdfDoc?.getPage(num).then((page: any) => {
            const canvasId = "pdf-canvas-" + num;
            const canvas = <any>document.getElementById(canvasId);
            const ctx = canvas.getContext("2d");
            const dpr = window.devicePixelRatio || 1;
            const bsr =
                ctx.webkitBackingStorePixelRatio ||
                ctx.mozBackingStorePixelRatio ||
                ctx.msBackingStorePixelRatio ||
                ctx.oBackingStorePixelRatio ||
                ctx.backingStorePixelRatio ||
                1;
            const ratio = dpr / bsr;
            const viewport = page.getViewport({ scale: pdfScale.value });
            canvas.width = viewport.width * ratio;
            canvas.height = viewport.height * ratio;
            canvas.style.width = viewport.width + "px";
            canvas.style.height = viewport.height + "px";
            ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
            const renderContext = {
                canvasContext: ctx,
                viewport: viewport,
            };
            page.render(renderContext);
            if (num < pdfPages.value) {
                renderPage(num + 1);
            }
        });
    };
    function openModal() {
        state.visible = true;
        nextTick(() => {
            loadFile(props.file.previewPath);
        })
    }
    function handleCancel() {
        state.visible = false;
    }
    async function exportBtn() {
        try {
            state.downLoading = true
            if (!props.file?.path) {
                message.warning(`无地址,可供下载`)
                return;
            }
            await downloadBlobAsync(props.file?.path, props.file?.originalFileName, true)
        } catch (error: any) {
            message.error(error)
        } finally {
            state.downLoading = false
        }
    }
    
    defineExpose({
        openModal
    })
    </script>
    <style>
    #videoContainer {
        height: 500px;
        width: 100%;
        overflow: auto;
        .canvas {
            width: 80% !important;
            margin: 0 auto;
        }
    }
    
    .preview-btns-posi {
        position: absolute;
        top: 10px;
        right: 50px;
    }
    </style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    /**下载文件 */
    export const downloadBlobAsync = (blob: Blob | string, fileName: string, isUrl = false) => {
      return new Promise<void>((resolve, reject) => {
        try {
          //对于标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
          //IE10以上支持blob但是依然不支持download
          if ('download' in document.createElement('a')) {
            //支持a标签download的浏览器
            const link = document.createElement('a'); //创建a标签
            link.download = fileName; //a标签添加属性
            link.style.display = 'none';
            link.href = isUrl ? blob as string : URL.createObjectURL(blob as Blob);
            document.body.appendChild(link);
            link.click(); //执行下载
            URL.revokeObjectURL(link.href); //释放url
            document.body.removeChild(link); //释放标签
          } else {
            //其他浏览器
            (navigator as any)?.msSaveBlob(blob, fileName);
          }
        } catch (error) {
          console.log(error)
          reject(error);
        } finally {
          setTimeout(() => {
            resolve()
          }, 500)
        }
      })
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
  • 相关阅读:
    敏捷实践之单元测试及最佳实践
    初识OAuth2.0
    java毕业设计城镇保障性住房管理系统mybatis+源码+调试部署+系统+数据库+lw
    六级易混词整理
    手写 Vue 系列 之 从 Vue1 升级到 Vue2
    因势而变,因时而动,Go lang1.18入门精炼教程,由白丁入鸿儒,Go lang泛型(generic)的使用EP15
    【毕业设计之微信小程序系列】基于微信小程序的餐厅点餐小程序的设计与实现
    光伏发电预测(LSTM、CNN_LSTM和XGBoost回归模型,Python代码)
    Shell编程
    【ArcGIS Pro二次开发】(65):进出平衡SHP转TXT、TXT转SHP
  • 原文地址:https://blog.csdn.net/shibaweijin/article/details/134444279
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号