javascript
复制代码
<script>
import * as PDFJS from 'pdfjs-dist'
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.js');//解决pdf.js中文乱码问题
import pdf from 'vue-pdf-signature'
// 中文PDF加载空白引入依赖
import CMapReaderFactory from 'vue-pdf-signature/src/CMapReaderFactory'
export default {
components: {pdf},
data(){
return{
pdfPages: 0,//pdf页数
pdfDoc: null,//pdf对象
}
},
mounted() {
this.getFileData();
},
methods:{
//获取后台返回的文件流
getFileData() {
this.$http.post("/doc/docarchivemanagereceive/preview", {
...this.from,
}, {
responseType: 'blob',
}).then(({data: res}) => {
//pdf-main 滚动条回到顶部
this.$nextTick(() => {
document.getElementsByClassName('pdf-main')[0].scrollTop = 0
})
const blob = new Blob([res], {type: 'application/pdf'})
let fileUrl = URL.createObjectURL(blob)
this.loadFile(fileUrl)
})
},
//加载pdf文件
loadFile(url) {
const loadingTask = pdf.createLoadingTask({
url: url,
cMapPacked: true,
CMapReaderFactory
});
loadingTask.promise.then((pdf) => {
this.pdfDoc = pdf;
this.pdfPages = pdf.numPages;
this.$nextTick(() => {
for (let i = 0; i < this.pdfPages; i++) {
this.renderPage(i + 1, i) // 从第一页开始渲染
}
})
}).catch((err) => {
console.error("pdf 加载失败", err);
this.$message.error("PDF文件打开失败");
});
},
//获取分辨率
getDeviceDPI() {
var dpi = 96; // 默认值 96dpi
if (window.screen && window.screen.deviceXDPI && window.screen.logicalXDPI) {
dpi = window.screen.deviceXDPI / window.screen.logicalXDPI * dpi;
} else if (window.devicePixelRatio) {
dpi = dpi * window.devicePixelRatio;
}
return dpi;
},
//渲染pdf页
renderPage(num, index, scale = 1.5, rotation = 0) {
let deviceDPI = this.getDeviceDPI();
this.pdfDoc.getPage(num).then((page) => {
var viewport = page.getViewport({
scale: scale,
rotation: page.getViewport({scale: scale}).rotation + rotation
});
// Support HiDPI-screens.
var outputScale = window.devicePixelRatio || 1;
var canvas = document.getElementById('pdfCanvas' + index);
var context = canvas.getContext('2d');
canvas.width = Math.floor(viewport.width * outputScale);
canvas.height = Math.floor(viewport.height * outputScale);
canvas.style.width = Math.floor(viewport.width) + "px";
canvas.style.height = Math.floor(viewport.height) + "px";
canvas.parentNode.style.width = canvas.width + 'px';
canvas.parentNode.style.height = canvas.height + 'px';
var transform = outputScale !== 1
? [outputScale, 0, 0, outputScale, 0, 0]
: null;
var renderContext = {
canvasContext: context,
transform: transform,
viewport: viewport
};
page.render(renderContext);
})
//pdfjs-dist 2.0.945版本getViewport(scale)的传参方式
/* this.pdfDoc.getPage(num).then((page) => {
var scale = 816 / page.getViewport(1).width * (window.devicePixelRatio || 1);
var scaledViewport = page.getViewport(scale);
var canvas = document.getElementById('pdfCanvas' + index);
var context = canvas.getContext('2d');
canvas.width = scaledViewport.width;
canvas.height = scaledViewport.height;
var renderContext = {
canvasContext: context,
viewport: scaledViewport
};
page.render(renderContext);
})*/
},
}
}
</script>