乐趣区

关于typescript:React-Hooks使用pdfjsdist

零碎页面中有时候会有一些加载 pdf 资源的性能需要,pdfjs-dist 这个插件能够满足要求。
解决步奏:申请 -> 转换 -> 加载
这里应用的版本是 2.2.228
申请有两种,一种能够是 Url 链接申请。一种是二进制文件。代码上差异不大, 业务逻辑解决如下:

const winW = (document.querySelector('.pdf-calssname') as HTMLDivElement).getBoundingClientRect().width;

const loadingFile = PDFJS.getDocument('your url'); // URL
const laodingFile = PDFJS.getDocument({data:atob(blod)}); // 二进制文件

//loading....
loadingFile.promise.then((pdf)=>{
    const nums = pdf.numPages;
    setpageNum(new Array(nums).fill(1)); // pageNum variable
    for(let i =1;i<nums;++i){pdf.getPage(i).then((page:any)=>{const viewport:any = page.getViewport(i);
            const scale:any = (winW / viewport.width).toFixed(2); //url
            cosnt scale:any = (winW /viewport.width *viewport.scale).toFixed(2) // 二进制文件流
            const scaledViewport = page.getViewport({scale:Math.max(scale,1)*2});
            const canvas:any = document.getElementById('the-canvas'+i);
            const context = canvas.getContext('2d');
            canvas.height = Math.ceil(scaleViewport.height);
            canvas.width = Math.ceil(scaleViewport.width);
            const renderContext ={
                canvasContext:context,
                viewport:scaledViewport,
            }
            const render:any = page.render(renderContext);
            render.then((=>{})
        })
    }
},(err)=>{console.log(err);
})

局部 tsx 代码如下:

<div className = 'pdfdetail-innderbox'>
    {pageNum.map((v:number,i:number)=>{<canvas key={i} id = {`the-canvas${i+1}`} className = 'pdf-content'>
        })
    }
</div>
退出移动版