H5预览PDF,集成在Android、IOS里,出于兼容性考虑,使用pdf.js。
网上很多教程,但是pdf.js的版本更新的很快,从github上下载最新版本,基本上都不适用,此处给出一个比较旧的版本1.9.426的使用方法,胜在简单
pdfjs-1.9.426下载地址
https://pan.baidu.com/s/1wW6P-fdHpiEHD_zME0pIXQ
qtom
前端
主要文件 pdfjs-1.9.426-dist/web/viewer.html
将解压的内容放到服务器中(如tomcat的项目的资源文件夹中),使用url地址打开viewer.html,结果如下:(该pdf是web目录下的compressed.tracemonkey-pldi-09.pdf–控件自带)
打开其他的PDF:(在url中添加file参数即可,且可实现跨域访问)
后台
演示使用数据流的方式加载给前端返回pdf。pdf的来源为域外,此处后台做了一个代理的作用
public String pdf(HttpServletRequest request, HttpServletResponse response) throws IOException{
String url = "http://www.baidu.com";
InputStream is = null;
OutputStream outputStream = null;
try {
is = new URL(url).openStream();
outputStream = response.getOutputStream();
response.setContentType("application/pdf");
int len=-1;
byte[] b=new byte[1024];
while((len=is.read(b))!=-1){
outputStream.write(b,0,len);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(is!=null){
is.close();
}
if(outputStream!=null){
outputStream.flush();
outputStream.close();
}
}
return null;
}