Angualr1 简单使用PDF.js查看字节流PDF文件

怕你不是斯巴达!!

需求介绍

    前端请求并在线查看PDF文件,PDF文件通过后台以字节流返回

一,导入PDF.JS

    将下载的pdf.js中的pdf.js和pdf.worker.js复制到项目中的

插件文件夹(如:lib),然后在项目的入口文件中注册

入口文件中注册

二,控制器请求文件,并通过PDF.JS打开

define(
  ['app', 'pdfjs','ngDraggable',], function(app,pdfjs) {
    var deps = ['$modal', '$rootScope'];
    function directive($modal ,$rootScope) {
        return {
            templateUrl: "views/chat/ChatMsgContent.html",
            replace: true,
            link: function($scope, elem, attrs) {
                $scope.pdfPage = 1;
                $scope.pdfPageMax = 1;
                $scope.pdfscale = 1;
                $scope.saveURL = 'saveURL';
                window.openPDF =  function openPDF(attachId){
                    var getattachId = attachId;
                    var url = $scope.baseUrl + "fileUploadController/downFile?fileId=" + getattachId;
                        if (/-pdf/g.test(getattachId)) {
                            var str = getattachId;
                            var replacestr = str.substring(0,str.length-4);
                            $("#downLoadPDF").attr('href',$scope.baseUrl + "fileUploadController/downFile?fileId=" + replacestr);
                        }else{
                            $("#downLoadPDF").attr('href',url);
                        }
                        
                        $scope.pdfscale = 1;     $scope.pdfPage = 1;    $scope.saveURL = url;  //初始话数据
                       
                        $("#pdfPage").val(1);
                         
                        pdfjs.getDocument(url).then(function getPdfHelloWorld(pdf) {
                            var container = document.getElementById("PDFcontainer");
                            container.style.display = "flex"; 
                            $scope.pdfPageMax = pdf.pdfInfo.numPages;
                        
                            pdf.getPage($scope.pdfPage).then(function getPageHelloWorld(page) {
                                var scale = 1;
                                var viewport = page.getViewport(scale);
                                var canvas = document.getElementById('the-canvas');
                                var canvas_box = document.getElementById('the-canvas_box');
                                var context = canvas.getContext('2d');
                                canvas.height = viewport.height;
                                canvas.width = viewport.width;
                                
                                if((viewport.height > window.innerHeight * 0.85 || viewport.height > window.innerHeight - 165) && window.innerHeight <= 900){
                                    var initNum = window.innerHeight / viewport.height * 0.85;
                                    //canvas.style.transform = 'scale('+initNum+','+initNum+')';
                                    canvas_box.style.position = "relative";
                                    canvas_box.style.height = viewport.height*initNum + "px";
                                    canvas_box.style.width = viewport.width*initNum+ "px";
                                    
                                    canvas.style.position="absolute";
                                    canvas.style.left = "0px";
                                    canvas.style.top = "0px";
                                    
                                    $scope.pdfSetLeft = 0;
                                    $scope.pdfSetTop = 0;
                                    $scope.pdfoX = 0;
                                    $scope.pdfoY = 0;
                                    
                                    canvas_box.onmousedown=function(ev){
                                       var e=window.event || ev;
                                       //var Mydiv=document.getElementById("div");
                                       //获取到鼠标点击的位置距离div左侧和顶部边框的距离;
                                       var oX=e.clientX-canvas_box.offsetLeft;
                                       var oY=e.clientY-canvas_box.offsetTop;
                                       $scope.pdfoX = $scope.pdfoX == 0?oX:$scope.pdfoX;
                                       $scope.pdfoY = $scope.pdfoY == 0?oY:$scope.pdfoY;
                                       
                                       var maxOY = viewport.height - viewport.height*initNum;
                                       var maxOX = viewport.width - viewport.width*initNum;
                                       
                                       //当鼠标移动,把鼠标的偏移量付给div
                                       document.onmousemove=function(ev){
                                           //计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给DIV的左边距和上边距,div就会跟着移动
                                           var e= window.event|| ev;
                                           var theLeft = e.clientX-$scope.pdfoX;
                                           var theTop = e.clientY-$scope.pdfoY;
                                           if(theLeft <= 0 && Math.abs(theLeft) <= maxOX ) $scope.pdfSetLeft = theLeft;
                                           if(theTop <= 0 && Math.abs(theTop) <= maxOY ) $scope.pdfSetTop = theTop;
                                           
                                           canvas.style.left = $scope.pdfSetLeft+"px";
                                           canvas.style.top = $scope.pdfSetTop+"px";
                                       }
                                       //当鼠标按键抬起,清除移动事件
                                       document.onmouseup=function(){
                                           document.onmousemove=null;
                                           document.onmouseup=null;
                                       }
                                      }
                                }
                                var renderContext = {
                                    canvasContext: context,
                                    viewport: viewport
                                };
                                page.render(renderContext);
                            });
                        }).catch(v=>{
                            console.warn(v);
                            var a = document.createElement('a');
                            if (/-pdf/g.test(getattachId)) {
                                var str = getattachId;
                                var replacestr = str.substring(0,str.length-4);
                                 a.href = $scope.baseUrl +  "fileUploadController/downFile?fileId=" + replacestr;
                            }else{
                                 a.href = url;
                            }
                            a.click();
                        });
                }
                $('#PDFlightbox').bind('click',function(){
                    var container = document.getElementById("PDFcontainer");
                    container.style.display = "none";
                });
                window.PDFDAO = function PDFDAO(daotype){
                     if(daotype == 'prev' && $scope.pdfPage != 1)$scope.pdfPage--;
                     if(daotype == 'next' && $scope.pdfPage != $scope.pdfPageMax)$scope.pdfPage++;
                     
                     if(daotype == 'big' && $scope.pdfscale < 2) $scope.pdfscale = $scope.pdfscale+0.1;
                     if(daotype == 'small' && $scope.pdfscale > 1) $scope.pdfscale = $scope.pdfscale-0.1;
                     
                     var gotoPage = parseInt($("#pdfPage").val());
                     if(daotype == 'go' && gotoPage >= 1 && gotoPage <= $scope.pdfPageMax) {
                        $scope.pdfPage = gotoPage;
                     }
                     $("#pdfPage").val($scope.pdfPage);
                     if($scope.pdfPage != 0 && $scope.pdfPage != $scope.pdfPageMax){
                         pdfjs.getDocument($scope.saveURL).then(function getPdfHelloWorld(pdf) {
                             pdf.getPage($scope.pdfPage).then(function getPageHelloWorld(page) {
                                 var scale = $scope.pdfscale;
                                 var viewport = page.getViewport(scale);
                                 var canvas = document.getElementById('the-canvas');
                                 var context = canvas.getContext('2d');
                                 canvas.height = viewport.height;
                                 canvas.width = viewport.width;
                                 var renderContext = {
                                     canvasContext: context,
                                     viewport: viewport
                                 };
                                 page.render(renderContext);
                             });
                         });
                     }   
                }
               
            }
        }
    }
    directive.$inject = deps;
    return app.lazy.directive('fcPdf', directive);
});

三,view层定义模块
1.模版样式

#PDFcontainer{position: fixed;top: 0px;left: 0px;height: 100%;width: 100%; z-index: 6;}
.lightboxCover{position: fixed;top: 0px;left: 0px;height: 100%;width: 100%; z-index: 7;opacity: 0.4;display: block;background-color: rgb(0, 0, 0);}
.lightbox{z-index: 8;}
.itermText_Center { display: flex; -webkit-box-align: center;-webkit-align-items: center;-ms-flex-align: center;align-items: center;-webkit-box-pack: center;-webkit-justify-content: center;-ms-flex-pack: center;justify-content: center;}
#Dao{padding-top: 20px; position: fixed; bottom: 20px; width: 500px;left: 50%; margin-left: -250px;}
#Dao a{display: inline-block; padding: 3px;margin: 5px;background: #fff; text-align: center; overflow: hidden; border-radius: 2px; box-shadow: 0 0 5px #eee;}
#pop{position: relative;}

#the-canvas_box{background-color: #fff;  }
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/  
#the-canvas_box::-webkit-scrollbar  
{ width: 5px;   height: 5px;   background-color: #F5F5F5;  }  
  
/*定义滚动条轨道 内阴影+圆角*/  
#the-canvas_box::-webkit-scrollbar-track  
{  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);  border-radius: 10px;   background-color: #F5F5F5;  }  
  
/*定义滑块 内阴影+圆角*/  
#the-canvas_box::-webkit-scrollbar-thumb  
{  border-radius: 10px;  -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);  background-color: #555;  }  
    2.HTML模版
         <div id="PDFcontainer" class="itermText_Center" style="display: none;">
          
            <div class="lightboxCover" id="PDFlightbox"></div>
            
            <div class="lightbox itermText_Center" >
                <div id="pop" class="pop">
                    <div id="the-canvas_box" style="overflow:auto;">
                         <canvas id="the-canvas"></canvas>
                    </div>
                    <div id="Dao" class="pop" ng-show="pdfPageMax != 1">
                        <a href="javascript:PDFDAO('prev');">上一页</a>
                        <a href="javascript:PDFDAO('next');">下一页</a>
                        
                        <a href="javascript:PDFDAO('big');" style="width:20px;">+</a>
                        <a href="javascript:PDFDAO('small');" style="width:20px;">-</a>
                        
                        <a href="" id="downLoadPDF" style="float:right;">下载 </a>
                        
                        <div class="itermText_Center" style="float:right;">
                          <input type="text" id="pdfPage" style="display: inline-block; padding: 3px;margin: 5px;width:25px;height:24px;">
                          <a href="javascript:PDFDAO('go');">GO</a>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>

四,PDF.JS内配置路径修改

原文件workerSrc
修改后workerSrc

注意:PDF.JS有多个workerSrc都要修改成导入项目后的路径

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、垂直对齐 如果你用CSS,则你会有困惑:我该怎么垂直对齐容器中的元素?现在,利用CSS3的Transform,...
    kiddings阅读 8,419评论 0 11
  • 这篇文字里我会介绍50 个便于使用的 CSS2/CSS3 代码片段给所有的WEB专业人员. 选择IDE开发环境来存...
    JamHsiao_aaa4阅读 5,261评论 0 3
  • 各种纯css图标 CSS3可以实现很多漂亮的图形,我收集了32种图形,在下面列出。直接用CSS3画出这些图形,要比...
    剑残阅读 13,307评论 0 8
  • 《如何阅读一本书》读后感 这是一本实用型的图书,主要内容就如同书名所诉,是教你如何去阅读一本书。很有意思的是,知道...
    奕风少年520阅读 1,409评论 0 0
  • 虹影成诗 【孤独感】 孤独感这东西没由来已久,似乎与灵魂共生。我很孤独,从头发到脚趾头。害怕一个人的时候,更害怕明...
    猪二十四阅读 2,571评论 0 0

友情链接更多精彩内容