最近項目要求在線顯示pdf,一頓搜索以後感受pdf.js還不錯,可是一直存在一個問題:跨域訪問,pdf.js不能直接跨域,最後用後臺服務將url的pdf轉成byte[],而後用pdf.js解析data,這樣就成功解決跨域問題了,跨域
解析urlbash
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 加載dataui
loadingTask = pdfjsLib.getDocument({data:data});//pdf.js的function用來代替url
複製代碼