Vue + ElementUI集成pdf.js 文件,预览pdf 文件

Posted 在奋斗的大道

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue + ElementUI集成pdf.js 文件,预览pdf 文件相关的知识,希望对你有一定的参考价值。

步骤总结

第一步:下载pdf.js

资源在此下载:

第二步:  解压

打开Vue项目的config/index.js文件。查看资源目录是static文件夹。

 所以将解压后的文件夹放入项目的static目录下,如图:

 

第三步:使用

在新建的vue文件中,代码如下。

<template>
  <div class="showPdf">
    <iframe :src="pSrc" width="100%" height="100%"></iframe>
  </div>
</template>
 
<script>
export default {
  name: 'App',
  data () {
    return {
      pSrc: ''
    }
  },
  methods: {
    loadPDF () {
      //pdf文件地址  测试可用
      let baseurl = 'http://192.168.1.74:8015/solr/api/arch/previewPDF'
      //根据实际情况 通过相对路径找到viewer.html
      this.pSrc = '../../../static/pdf/web/viewer.html?file=' + encodeURIComponent(baseurl)
    }
  },
  mounted () {
    this.loadPDF()
  }
}
</script>
 
<style>
.showPdf{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    bottom: 0;
}
</style>

第四步:SpringBoot后台服务接口源码:

	@RequestMapping(value = "/previewPDF")
	public ResponseEntity<byte[]> previewPDF() throws IOException {
		File tempFile = new File("D:\\\\demo.pdf");
		// 2)读取文件到字节数组
		byte[] bytes = FileUtils.readFileToByteArray(tempFile);

		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", "pdf 文件预览测试");
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
	}

温馨提示:打开页面会报错:file origin does not match viewer's。这是跨域问题,解决办法如下,打开viewer.js文件,注释掉这三行代码即可。

//if (fileOrigin !== viewerOrigin) {
//  throw new Error('file origin does not match viewer\\'s');
//}

PDF文件预览效果展示:

 

以上是关于Vue + ElementUI集成pdf.js 文件,预览pdf 文件的主要内容,如果未能解决你的问题,请参考以下文章

Vue.js项目集成ElementUI

vue 集成 element ui

通过前端js给远程PDF文件加水印

Vue学习总结23.Vue UI框架 ElementUi的使用

springboot+vue+mysql代码生成 集成系统管理

SpringBoot + Vue + ElementUI 实现后台管理系统模板