本文中使用的PDF.js组件版本为3.11.174(最新版使用上会有所不同),引入文件如下:
首先页面定义一个隐藏的弹窗块(此处用ElementUI的Dialog组件)
<el-dialog ref="dialogPDF" :title="pdffile.name" center :visible.sync="isPDFVisible" width="80%" :close-on-click-modal="true" :show-close="true"><div>@*<canvas id="pdf-canvas"></canvas>*@<!--由于是要展示所有面面,所以所有页面都分别绑定一个canvas--><canvas ref="pdf-canvas" v-for="num in pdfPages"></canvas></div>
</el-dialog>
绑定的Vue Data:
data: function() {return {pdffile: {},isPDFVisible: false,pdfPages: 0,..........}
}
要展示的文件这里集成在一个上传组件中,如代码所示:
<el-form-item label="附件" prop="FileIDsArray"><div style="max-height:512px;overflow-x:auto;"><el-upload ref="upload_attach" :file-list="editForm.FileInfos" drag list-type="picture-card" multiple :limit="maxUpload" :on-exceed="handleExceed":action="uploadUrl" :auto-upload="autoupload" @*:headers="headers"*@ :data="uploadParam" :on-change="handleChange1" :before-upload="beforeUpload":on-success="uploadSuccess1" @*:on-preview="previewPic"*@ :on-remove="removeAttachFile1" :before-remove="beforeRemove" :class="{hideUnload:notAttachUploader}">@*<em class="el-icon-plus"></em>*@<em class="el-icon-upload"></em><div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div><div slot="file" slot-scope="{file}">@*<img class="el-upload-list__item-thumbnail":src="file.url" alt="">*@<span>{{file.name}}</span><span class="el-upload-list__item-actions"><span class="el-upload-list__item-preview" style="font-size: inherit;" v-show="!!file && file.name.slice(-4).toLowerCase()=='.pdf'"@@click="handleViewFile(file)"><i class="el-icon-zoom-in"></i></span><span class="el-upload-list__item-delete"@@click="handleDownload(file)"><i class="el-icon-download"></i></span><span class="el-upload-list__item-delete"@@click="$refs.upload_attach.$refs['upload-inner'].onRemove(file);"><i class="el-icon-delete"></i></span></span></div></el-upload></div>
</el-form-item>
重点是在显示PDF文件内容的方法——handleViewFile(file):
handleViewFile: function (file) {var pThis = this;this.pdffile = file;this.isPDFVisible = true;this.$nextTick(function () {//const canvas = document.getElementById('pdf-canvas');pdfjsLib.getDocument(file.url).promise.then(function (pdfDoc) {pThis.pdfPages = pdfDoc.numPages;//由于canvas.getContext('2d')必须是在生成DOM并显示的情况下操作,由此需先"isPDFVisible=true"显示出组件,并在$nextTick完成DOM加载后再处理pdf内容的渲染:pThis.$nextTick(function () {for (var i = 1; i <= pThis.pdfPages; i++) {const canvas = pThis.$refs["pdf-canvas"][i - 1];pdfDoc.getPage(i).then(function (page) {const viewport = page.getViewport({ scale: 1 });const context = canvas.getContext('2d');canvas.height = viewport.height;canvas.width = viewport.width;page.render({canvasContext: context,viewport: viewport});});}});});});
},
参考文章:
PDF.js 示例简介:
https://blog.csdn.net/github_36738403/article/details/131325145
如何显示整体PDF(不仅仅是一页)PDF.JS:
https://www.codenong.com/cs108161952/