vue3 + ts 实现预览pdf
时间: 2023-11-25 08:49:35 浏览: 123
以下是使用Vue3和TypeScript实现预览PDF的步骤:
1.安装依赖
```bash
npm install vue-pdf-embed pdfjs-dist --save
```
2.在Vue组件中引入插件
```typescript
<template>
<div>
<vue-pdf-embed :src="pdfUrl" :page="1" :scale="1.5" />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import VuePdfEmbed from 'vue-pdf-embed';
export default defineComponent({
name: 'PdfPreview',
components: {
VuePdfEmbed,
},
data() {
return {
pdfUrl: 'http://example.com/example.pdf', // PDF文件的URL地址
};
},
});
</script>
```
3.调用后端接口获取PDF文件流
```typescript
import axios from 'axios';
axios({
url: '/api/getPdf',
method: 'get',
responseType: 'blob', // 设置响应类型为blob
}).then((res) => {
const blob = new Blob([res.data]); // 创建一个blob
const url = URL.createObjectURL(blob); // 获取blob的URL
this.pdfUrl = url; // 将URL赋值给Vue组件中的pdfUrl
});
```
4.在浏览器中预览PDF文件
```typescript
const link = document.createElement('a');
link.download = 'example.pdf'; // 设置文件名
link.style.display = 'none';
link.href = url; // 设置链接地址
document.body.appendChild(link);
link.click(); // 模拟点击链接
document.body.removeChild(link); // 移除链接
```
阅读全文
相关推荐
















