PDF file preview, print

There are many ways to preview the front-end pdf files.

html元素:<iframe>、<embed>

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

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

Note: Using the <embed> tag will cause incompatibilities with lower versions of IE, and previews cannot be implemented in lower versions of IE.

It can be printed through iframe, embed, or using the browser itself.

vue-plugin

vue-pdf(不推荐)

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

Install

npm install --save vue-pdf-signature

use:

Single pdf preview and print

<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>

Guess you like

Origin blog.csdn.net/my__flower/article/details/129814730