一。vue-pdf
1. 安装vue-pdf
npm install --save vue-pdf
2.页面引入 js部分
import pdf from "vue-pdf";
data(){
return {
pdfUrl: "",
pageTotal: 0,
}
}
mounted(){
this.pdfUrl = pdf.createLoadingTask(pdf文件路径url);
// 获取页码
this.pdfUrl.promise .then((pdf) => (this.pageTotal = pdf.numPages))
.catch((error) => {});
}
3.html部分
<pdf
v-for="item in pageTotal"
:src="pdfUrl"
:key="item"
:page="item"
>
</pdf>
二、pdfJs
需要下载PDF.js库。您可以从官方GitHub仓库(https://github.com/mozilla/pdf.js)下载最新版本的PDF.js。
1.引入
Vue项目中找到public/index.html文件,并在文件的标签内添加以下代码以引入PDF.js库
<script src="./pdfjs/build/pdf.js"></script>
2.Vue 组件中使用元素展示 PDF 页面
<template>
<div>
<canvas ref="pdfCanvas"></canvas>
</div>
</template>
3.使用 PDF.js 提供的 API 加载和渲染 PDF 文件
mounted() {
this.loadPDF();
},
methods: {
async loadPDF() {
const pdfUrl = 'path/to/your/pdf/file.pdf'; // 替换为您的PDF文件路径
const loadingTask = window.PDFJS.getDocument(pdfUrl);
const pdf = await loadingTask.promise;
const canvas = this.$refs.pdfCanvas;
const context = canvas.getContext('2d');
const page = await pdf.getPage(1); // 加载第一页
const viewport = page.getViewport({ scale: 1 });
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext);
}
}
4.页面切换和缩放
<template>
<div>
<canvas ref="pdfCanvas"></canvas>
<button @click="previousPage">Previous Page</button>
<button @click="nextPage">Next Page</button>
</div>
</template>
5.页面切换和缩放功JavaScript部分
data() {
return {
pdf: null,
currentPage: 1
};
},
mounted() {
this.loadPDF();
},
methods: {
async loadPDF() {
// ...
},
async previousPage() {
if (this.currentPage > 1) {
this.currentPage--;
await this.renderPage(this.currentPage);
}
},
async nextPage() {
if (this.currentPage < this.pdf.numPages) {
this.currentPage++;
await this.renderPage(this.currentPage);
}
},
async renderPage(pageNumber) {
const page = await this.pdf.getPage(pageNumber);
const viewport = page.getViewport({ scale: 1 });
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);
}
}