vue 实现pdf
Vue 中实现 PDF 预览与下载
使用 pdf.js 预览 PDF
安装 pdfjs-dist 库:
npm install pdfjs-dist
在 Vue 组件中引入并渲染 PDF:
<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
};
page.render(renderContext);
}
}
};
</script>
使用 vue-pdf 插件
安装插件:

npm install vue-pdf
组件中使用:
<template>
<pdf :src="pdfUrl"></pdf>
</template>
<script>
import pdf from 'vue-pdf';
export default {
components: { pdf },
data() {
return {
pdfUrl: '/sample.pdf'
};
}
};
</script>
实现 PDF 下载
通过 <a> 标签直接下载:

<template>
<a :href="pdfUrl" download="document.pdf">Download PDF</a>
</template>
使用 Blob 对象动态下载:
<script>
export default {
methods: {
downloadPdf() {
fetch('/sample.pdf')
.then(response => response.blob())
.then(blob => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'document.pdf';
link.click();
});
}
}
};
</script>
服务端生成 PDF
使用 html2pdf.js 将 HTML 转为 PDF:
npm install html2pdf.js
组件示例:
<template>
<div ref="content">
<!-- 需要转换为 PDF 的内容 -->
</div>
<button @click="generatePdf">Export PDF</button>
</template>
<script>
import html2pdf from 'html2pdf.js';
export default {
methods: {
generatePdf() {
const element = this.$refs.content;
const opt = {
margin: 1,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
};
</script>
注意事项
- 跨域问题需确保服务器配置 CORS 头
- 大文件 PDF 建议分页加载
- 动态生成 PDF 时注意浏览器兼容性
- 移动端需测试触控交互体验






