装置插件
npm install vue-pdf
yarn add vue-pdf
文档链接:https://github.com/FranckFrei…
间接应用插件的打印,会呈现乱码,须要批改 node_modules 源码
具体代码的批改参照下方文档链接
文档链接:https://github.com/FranckFrei…
一、申请后端,后端返回文档流的模式:
预览
预览款式(以多页为例)
html
// 其余代码省略...
<div class="max-height">
// 多页(蕴含只有一页的状况)
<pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i" style="width: 100%" ref="waybillRef"></pdf>
// 单页(打乱原有布局,组件放在这里是为了演示不便)
<pdf :src="codeSrc" ref="codeRef"></pdf>
</div>
script
import pdf from 'vue-pdf';
import { getPDF } from '@/assets/scripts/utils'; // 须要申请的后盾PDF文档流接口
/**
* getPDF阐明:
* 后端有多个不同的pdf接口,前端依据url管制,将后端文档流和文件名称,用Promise的形式返回
* 其余代码略...
* axios
.get(url, { responseType: 'blob' })
.then((response) => {
let fileName = decodeURIComponent(
response.headers['content-disposition'].replace(
/.+filename=(.+)/g,
'$1'
)
)
resolve({ data: response.data, name: fileName })
})
.catch((error) => {
reject(error)
})
*
**/
export default {
components: { pdf },
data() {
return {
pdfSrc: '',
codeSrc: '',
numPages: null,
}
},
methods: {
// 进入页面就申请后端接口用于预览
getPageData() {
// 其余代码省略...
getPDF(url).then(res => {
let blob = window.URL.createObjectURL(
new Blob([res.data], {
type: 'application/pdf;charset=UTF-8',
})
);
this.pdfSrc = pdf.createLoadingTask(blob);
this.pdfSrc.promise.then(pdf => {
this.numPages = pdf.numPages
})
})
}
}
}
打印
print(ref) {
if (ref==='waybillRef') {
// 多页是循环来的,ref是数组,须要加上下标
this.$refs[ref][0].print();
} else {
this.$refs[ref].print();
}
},
多页的写法–打印多页的款式(临时bug未解决,见下图)
多页的写法–打印单页的款式
单页的写法–打印单页的款式
下载
script
import { downloadPDF } from '@/assets/scripts/utils';
/**
* downloadPDF阐明:
* 下载PDF文件流-->通过url先调用前文的getPDF-->前端做下载
* 其余代码略...
* getPDF(url).then(res => {
let url = window.URL.createObjectURL(
new Blob([res.data], {
type: 'application/pdf;charset=UTF-8',
})
);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.download = res.name;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})
*
**/
method: {
download() {
downloadPDF(url);
},
}
下载后的后果
二、申请OSS, 返回url的模式:
【页面阐明】(其中下载就是前述【下载后的后果】局部)
预览
性能:点击PDF文件的放大icon,弹出预览弹窗
html
// 其余代码省略...
<div class="max-height">
// 因为这里的页面的pdf页数不确定,故应用多页
<pdf v-for="i in numPages" :key="i" :src="pdfSrc" :page="i" style="width: 100%></pdf>
</div>
script
// 其余代码省略...
import pdf from 'vue-pdf';
export default {
components: { pdf },
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
numPages: null,
}
},
methods: {
// 点击放大
handlePreview(file) {
this.dialogImageUrl = pdf.createLoadingTask(file.url);
this.dialogImageUrl.promise.then(pdf => {
this.numPages = pdf.numPages // 这里拿到以后pdf总页数
})
this.dialogVisible = true;
}
}
}
预览款式(以多页为例)
发表回复