vue 实现pdf预览
实现PDF预览的方法
在Vue项目中实现PDF预览可以通过多种方式完成,以下是几种常见的方法:
使用PDF.js库
PDF.js是Mozilla开发的一个开源库,可以直接在浏览器中渲染PDF文件。
安装PDF.js:
npm install pdfjs-dist
在Vue组件中使用:

<template>
<div>
<canvas ref="pdfCanvas"></canvas>
</div>
</template>
<script>
import * as pdfjsLib from 'pdfjs-dist';
export default {
props: ['pdfUrl'],
mounted() {
this.renderPDF();
},
methods: {
async renderPDF() {
const loadingTask = pdfjsLib.getDocument(this.pdfUrl);
const pdf = await loadingTask.promise;
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 1.0 });
const canvas = this.$refs.pdfCanvas;
const context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext).promise;
}
}
};
</script>
使用vue-pdf组件
vue-pdf是一个封装了PDF.js的Vue组件,使用更简单。
安装vue-pdf:

npm install vue-pdf
在Vue组件中使用:
<template>
<pdf :src="pdfUrl"></pdf>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: {
pdf
},
data() {
return {
pdfUrl: '/path/to/document.pdf'
}
}
}
</script>
使用iframe嵌入
最简单的PDF预览方式,但功能和样式受限。
<template>
<iframe
:src="pdfUrl"
width="100%"
height="600px"
style="border: none;">
</iframe>
</template>
<script>
export default {
data() {
return {
pdfUrl: '/path/to/document.pdf'
}
}
}
</script>
使用Google Docs Viewer(在线服务)
通过Google的在线服务预览PDF,需要网络连接。
<template>
<iframe
:src="'https://docs.google.com/viewer?url=' + encodeURIComponent(pdfUrl) + '&embedded=true'"
width="100%"
height="600px"
style="border: none;">
</iframe>
</template>
注意事项
- PDF.js和vue-pdf需要处理跨域问题,如果PDF文件来自不同源
- 对于大文件,考虑实现分页加载以提高性能
- 移动端需要调整视图大小以适应不同屏幕
- 某些方法可能需要后端配合设置正确的Content-Type头
以上方法可以根据项目需求选择最适合的实现方式。PDF.js提供最灵活的控制,vue-pdf简化了集成过程,iframe最简单但功能有限。






