前端如何预览pdf文件流

1. PDF组件选型

通过查找资料,可以找到如下几种方案,其中最为成熟的方案是vue-pdf

1. iframe 既可以用来浏览本地static下的文档,也可以预览后端返回的文件流文档

2. vue-pdf 较为完善的vue预览pdf的方案

3. vueshowpdf 网络上找到的一个他人封装的pdf组件

优点

缺点 原理

iframe/object/embed

简单易用,包含了翻页,打印,缩放等内嵌功能 无法禁止打印 将pdf作为插件内嵌再这三个HTML标签内
vueshowpdf 样式简单清爽,包含翻页,缩放功能,可以禁止打印 在不修改源码的情况下无法自定义相关样式,无进度加载提示,加载完成前会出现白屏 基于底层pdf.js实现

vue-pdf

样式组件可自定义,包含加载进度,翻页,页内元素可交互等 固定宽高的比例,需要将包裹pdf的父容器尽可能调大才能显示完全 基于pdf.js实现

总结下来,

  • 如果只想 简单在页面嵌套PDF,使用iframe/object/embed是最好的选择,它不需要你自己去编写翻页组件,不需要去调整样式,用户体验佳。
  • 如果对 样式没有定制化  的需求,使用 vueshowpdf 也是非常不错,弹窗式的UI看起来会更加高大上。
  • 如果对 权限控制,样式定制需求高,使用 vue-pdf 是最好的选择,接口和属性较全,扩展能力强,自由度高。

2. Iframe使用步骤

2.1 使用与逻辑

逻辑:将后端返回的看不懂的文件流,设置成reponseType="arraybuffer",然后读取到返回的blob,再使用createObjectURL读取出url即可

 2.2 代码示例

<template>
    <iframe :src="src" frameborder="0" :style="iframeStyle" />
</template>

<script>

import { mapState } from 'vuex'
import { getNodeObjectData } from '@/modules/viewer/apis/service'

export default {
    name: 'pdfPanel',
    props: {
        node: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            src: ''
        }
    },
    computed: {
        ...mapState({
            innerHeight: (state) => state.viewerStore.setting['innerHeight']
        }),
        iframeStyle() {
            return {
                width: '100%',
                height: `${this.innerHeight - 130}px`
            }
        }
    },
    mounted() {
        return getNodeObjectData({
            meta_id: this.node.id
        })
        .then((res) => {
            const blob = new Blob([res], { type: 'application/pdf' })
            const url = window.URL.createObjectURL(blob)
            this.src = url
        })
    },
    methods: {
        handleFullScreen() {
            window.open(`${this.src}#filename=${this.node.name}`, "_blank")
        }
    }
}
</script>>

2.3 图文详解

1. 后端返回的是文件流,如下:

2. 接口请求设置responseType="arraybuffer"

export function getNodeObjectData(params) {
    return axios({
        url: `${apiPrefix}/pdf`,
        method: 'GET',
        params: params,
        responseType: 'arraybuffer'
    })
}

猜你喜欢

转载自blog.csdn.net/valsedefleurs/article/details/130825618