PDFjs使用总结

最近在项目中用到PDFJS查看浏览PDF文件,简单记下用法

jsp页面添加:<iframe src="js/pdfjs/web/viewer.html" width="100%" height="350px" id="Iframe"></iframe>

1、对于站点内路径直接赋值文件路径给SRCURL即可,不需要在后台去转换 ,对于跨域和用本地实际路径的文件加载可以把文件地址传到后台转成文件流加载,实际项目是从FTP下载文件得到的文件流 ,在这downloadFilePdf 只记了个简化版生成文件流 
   js

    var pathName=window.document.location.pathname;
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    var filePath = $("#filesrc").textbox("getValue");    
    if (filePath!=''){
        var srcurl=encodeURIComponent(projectName+"/downloadFilePdf.do?filePath="+filePath);
        $("#Iframe").attr("src","js/pdfjs/web/viewer.html?file="+srcurl+"");
    }

  conroller 后台得到文件流
  @RequestMapping(value = "/downloadFilePdf.do")
    public void downloadFilePdf(@RequestParam("filePath")String filePath,HttpServletRequest request, HttpServletResponse response) {
        try {            
            String filename = filePath.substring(filePath.lastIndexOf('/')+1);
            response.setHeader("Content-Type","application/pdf");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Content-Disposition", "attachment;filename="+filename);
            File file = new File(filePath);    
            FileInputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream returnStream = new ByteArrayOutputStream();          
                byte[] data = new byte[2048];
            int len = 0;
            int sum = 0;
            while ((len = inputStream.read(data))!= -1) {
                returnStream .write(data, 0, len);
                sum = len + sum;
            }
            byte[] returnBytes= returnStream .toByteArray();  
            response.getOutputStream().write(returnBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
                 
    }

2、选择文件加载浏览可以用以下方式得到文件的blob url 地址
  jsp: <label id="lblPdf">选择文件:</label> <input id="tbPdf" style="width: 200px" runat="server" name="PdfFile" type="file" οnchange="javascript:openPDF
(this);"/>

  js:function openPDF(file){
        if(!file.files||!file.files[0]){
            return;
        }    
        var f = file.files[0];  
        var filePath = null ;
          if (window.createObjectURL!=undefined) { // basic
            filePath = window.createObjectURL(f) ;
          }else if (window.webkitURL!=undefined) { // webkit or chrome
            filePath = window.webkitURL.createObjectURL(f) ;
          }else if (window.URL!=undefined) { // mozilla(firefox)
            filePath = window.URL.createObjectURL(f) ;
          }
          $("#Iframe").attr("src","js/pdfjs/web/viewer.html?file="+filePath +"");        

  }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值