vue2的项目,其中使用"pdfjs-dist的2的版本;
页面引入:
const PDFJS = require('pdfjs-dist')
PDFJS.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.min')
import { TextLayerBuilder,AnnotationLayerBuilder, SimpleLinkService } from 'pdfjs-dist/web/pdf_viewer'
import 'pdfjs-dist/web/pdf_viewer.css'
<div class="wrapper" id="pdf-container">
<div v-for="item in totals" :id="`page-${item}`" :key="item" class="pdf-box">
<canvas :id="`canvas-${item}`" class="canvas-pdf"></canvas>
</div>
</div>
// 接口获取数据
xxxapi().then(res=>{
var binaryData = [];
binaryData.push(res.data);
console.log(binaryData);
// 记得一定要设置application的类型
let url = window.URL.createObjectURL(
new Blob(binaryData, {
type: "application/pdf;charset=utf-8",
})
);
if (url) {
this.contentSpining=false
this.showPdf = true;
let source = { url: url };
PDFJS.getDocument(source).then(pdf => {
// 得到PDF的总的页数
let totalPage = pdf.numPages
let idName = 'canvas-pdf-'
// 根据总的页数创建相同数量的canvas
this.createCanvas(totalPage, idName)
for (let i = 1; i <= totalPage; i++) {
pdf.getPage(i).then((page) => {
let pageDiv = document.getElementById(`page-${i}`)
let viewport = page.getViewport(this.scale)
let canvas = document.getElementById(idName + i)
let context = canvas.getContext('2d')
canvas.height = viewport.height
canvas.width = viewport.width
this.viewHeight = viewport.height
let renderContext = {
canvasContext: context,
viewport
}
page.render(renderContext).then(() => {
return page.getTextContent()
}).then((textContent) => {
// 创建文本图层div
const textLayerDiv = document.createElement('div')
textLayerDiv.setAttribute('class', 'textLayer')
// 将文本图层div添加至每页pdf的div中
pageDiv.appendChild(textLayerDiv)
let textLayer = new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: page.pageIndex,
viewport: viewport
})
textLayer.setTextContent(textContent)
textLayer.render()
})
// 批注层
page.getAnnotations().then(annotations=>{
// const annoLayerDiv=document.createElement(`div`)
// annoLayerDiv.setAttribute('class', 'annotationLayer')
const annolayer = new AnnotationLayerBuilder({
pageDiv: pageDiv,
annotations: annotations,
pdfPage: page,
linkService: new SimpleLinkService(),
});
annolayer.render(viewport);
})
})
}
})
})