Previewing uploaded files or attachments is a common requirement in Vue projects. If the file is a PDF, vue-pdf is a straightforward option that can be dropped into a dialog and used directly.
Start by installing the package:
npm install --save vue-pdf
In the interface, the PDF can be displayed inside an el-dialog. Each page is rendered with a v-for, so the full document appears page by page once the total page count is known.
<el-dialog
title="附件预览"
:visible.sync="previewPdf"
width="60%"
top="5vh"
append-to-body
>
<pdf ref="pdf" v-for="i in numPages" :key="i" :src="url" :page="i"> </pdf>
</el-dialog>
The component needs to import vue-pdf, register it, and define a few basic fields in data: whether the preview dialog is open, the PDF URL, and the total number of pages.
<script>
import pdf from 'vue-pdf'
export default {
components:{
pdf
},
data(){
return {
previewPdf: false,
url: "http://192.168.2.222/test.pdf",
numPages: null,
}
},
methods: {
getNumPages() {
let loadingTask = pdf.createLoadingTask(this.url);
loadingTask.promise
.then((pdf) => {
this.numPages = pdf.numPages;
})
.catch((err) => {
console.error("pdf 加载失败", err);
});
},
}
</script>
The key part is getNumPages(). It creates a loading task from the PDF URL, waits for the file to load, and then reads pdf.numPages. Once that value is assigned to numPages, the loop in the dialog can render every page.
If loading fails, the error is caught and printed in the console. With this setup, online PDF preview becomes fairly direct: open the dialog, point url to the target file, call getNumPages(), and let the component render the document.