PDFJS跨域显示PDF文件的两种方法

首先使用文件流获取远程文件

@RequestMapping("getPdfFile")	
public void getRemoteFile(String url, HttpServletResponse response) {  
        InputStream inputStream = null;  
        try {  
            try {  
                String strUrl = url.trim();
                URL url=new URL(strUrl);
                //打开请求连接
                URLConnection connection = url.openConnection();
                HttpURLConnection httpURLConnection=(HttpURLConnection) connection;
                httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                // 取得输入流,并使用Reader读取
                inputStream = httpURLConnection.getInputStream();
                int bytesum = 0;
                int byteread = 0;
                byte[] buffer = new byte[1024];
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String("cbzm.pdf".getBytes()));
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                bytesum = 0;
                byteread = 0;
                buffer = new byte[1024];
                while ((byteread = inputStream.read(buffer)) != -1) {
                    bytesum += byteread;
                    toClient.write(buffer, 0, byteread);
                }
                toClient.flush();
                inputStream.close();
                
                toClient.close();
            } catch (IOException e) {  
                e.printStackTrace();
                inputStream = null;  
            }  
        } catch (Exception e) {  
            e.printStackTrace();
            inputStream = null;  
        }  
    }

接下来使用PDFJS的两种方式展示

第一种(JS方式):

第二种(viewer.html方式):

1.注释viewer.js中DEFAULT_URL

2.在viewer.html中增加以下代码

 

你可能感兴趣的:(java,pdf.js,pdfjs跨域)