vue整合pdfjs
浏览器是能直接接收pdf文件流的,pdf以iframe的格式嵌入到页面中。以防有需要的朋友,代码示例如下:
/**
sealPdfApi:接口,参数为data,返回值为pdf文件流;
*/
sealPdfApi(data).then(res => {
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
this.$notify.error({
title: "请使用google浏览器" });
} else {
var blob = new Blob([res], {
type: "application/pdf" });
this.pdfViewer = URL.createObjectURL(blob);//创建的pdf链接
window.open(this.pdfViewer);//打开窗口,也可以页面使用iframe,src等于上面的pdf链接
}
})
使用以上方法需要特别注意的一点就是接口调用时,响应类型必须是blob类型,一般可以在项目的通用接口配置中修改。
responseType: 'blob'
虽然这样的方法能正确显示pdf,但是对于公司的盖章需求有几个问题。
- 拖拽盖章,一个pdf可能需要盖多个章
- 盖章是需要调用后端接口的,接口参数需要每个印章在pdf中的位置
针对上面的需求,我一开始的想法是将想在iframe的外面包一层div,利用印章在div中的位置去获取对应的pdf坐标位置。但是这样另一个问题很难解决,如何在盖完章之后将章保留在页面上。想出来的方法相对来说都比较麻烦,感兴趣的大佬们可以尝试研究一下。
最终决定了一个方案,整合pdfjs,讲pdf用canvas的方式在页面上显示,在canvas的外层包裹一个div,获取印章在div块中的位置,在canvas中使用 ctx.drawImage()
方法来讲印章绘制到pdf中。
以下是整合pdfjs的组件部分代码,项目地址我会放在文章的底部:
export default {
name: 'Pdf',
props: {
url: {
type: String,
default: ''
},
type: {
type: String,
default: 'canvas'
},
pdfjsDistPath: {
type: String,
default: '.'
}
},
data() {
return {
pdfViewer: null,
pdfLinkService: null,
currentScale: '1.0',//缩放比例
loadingTask: null
}
},
methods: {
onPagesInit({
source }) {
source.currentScaleValue = this.currentScale
},