vue使用pdfjs-dist在电脑上展示PDF文件
<template>
<div>
<canvas ref="pdfCanvas"></canvas>
</div>
</template>
<script>
import pdfjsLib from 'pdfjs-dist/build/pdf';
export default {
props: {
pdfUrl: {
type: String,
required: true
}
},
mounted() {
this.renderPdf();
},
methods: {
renderPdf() {
const canvas = this.$refs.pdfCanvas;
const ctx = canvas.getContext('2d');
const loadingTask = pdfjsLib.getDocument(this.pdfUrl);
loadingTask.promise.then(pdf => {
console.log('PDF loaded');
pdf.getPage(1).then(page => {
const viewport = page.getViewport({ scale: 1.5 });
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext).promise.then(() => {
console.log('Page rendered');
});
}).catch(err => {
console.error('Cannot load page: ', err);
});
}).catch(err => {
console.error('Cannot load PDF document: ', err);
});
}
}
};
</script>
这段代码使用Vue框架和pdfjs-dist库来加载和渲染PDF文件。它首先在mounted
钩子中调用renderPdf
方法,该方法使用pdfjsLib.getDocument
获取PDF文档,然后获取第一页,并设置画布的尺寸以匹配视口,最后使用page.render
方法渲染页面到画布上。
评论已关闭