pdf文件预览、打印

前端 pdf 文件预览的方式有多种。

html元素:<iframe>、<embed>

<iframe :src="pdfUrl " style="width: 100%; height: 800px" />

<embed :src="pdfUrl " style="width: 100%; height: 800px" />

注意:使用该<embed>标签会存在低版本IE不兼容问题,在低版本IE中无法实现预览。

可通过iframe、embed,使用浏览器自带打印即可。

vue插件

vue-pdf(不推荐)

vue-pdf-signature(可以用,但打印出来的质量不如浏览器自带打印的)

安装

npm install --save vue-pdf-signature

使用:

单张 pdf 预览及打印

<template>
    <el-button @click="onPreview">点击</el-button>
    <el-dialog 
    title="预览" 
    append-to-body 
    :visible.sync="isPreview" 
    width="800px" 
    @closed="onClosed">
        <!-- 单张pdf -->
        <pdf ref="pdfRef" :src="pdfUrl" />
        <!-- 多张pdf -->
        <pdf :src="pdfUrl" v-for="i in numPages" :key="i" :page="i" />
        <span slot="footer" class="dialog-footer">
            <el-button @click="onClosed">取 消</el-button>
            <el-button @click="$refs.pdfRef.print()">确 定</el-button>
         </span>
    </el-dialog>
</template>

<script>
import pdf from "vue-pdf-signature";
// 如果在IE中预览pdf部分字符无法显示问题,需要引入CMapReaderFactory
// 传入配置 pdf.createLoadingTask({ url: url, cMapPacked: true, CMapReaderFactory, });
import CMapReaderFactory from "vue-pdf-signature/src/CMapReaderFactory";

export default {
  name: 'preview',
  components: { pdf },
  data() {
      return {
          pdfUrl: '',
          numPages: undefined
      };
  },
  methods: {
    onPreview(){
        const url = window.URL.createObjectURL(res);
        const params = {id:'2222'};
        downloadPDF(params).then(res => {
            const url = res.data;
            // 如果请求回来的 res.data,不是资源地址的pdf,而是文件流的话,需要转换一下
            // const url = URL.createObjectURL(res.data);
            const loadingTask = pdf.createLoadingTask({ url: url, });
            loadingTask.promise.then((pdf) => {
                this.pdfUrl = url;
                this.numPages = pdf.numPages;
            }).catch((err) => {
                console.error("pdf 加载失败", err);
            });
        });
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/my__flower/article/details/129814730