pdf.js 跨域访问远程服务器地址

2,172 阅读1分钟

最近项目要求在线显示pdf,一顿搜索之后感觉pdf.js还不错,但是一直存在一个问题:跨域访问,pdf.js不能直接跨域,最后用后台服务将url的pdf转成byte[],然后用pdf.js解析data,这样就成功解决跨域问题了,

解析url

  InputStream inputStream = null;
        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)");
            inputStream = httpURLConnection.getInputStream();
            BufferedInputStream    bin = new BufferedInputStream(inputStream);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedOutputStream     bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while (len != -1) {
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
           
            bout.flush();
            byte[] bytes = baos.toByteArray();
             return bytes
        } catch (IOException e) {
        }

pdf.js 加载data

loadingTask = pdfjsLib.getDocument({data:data});//pdf.js的function用来代替url