到官网下载 pdf.js 插件并解压 (地址: http://mozilla.github.io/pdf.js/ )
将解压的文件放到项目根目录。
访问本地:localhost:8080/web/viewer.html。成功显示默认pdf。
我们需要做的就是在项目路径后面参数拼接,格式如下
localhost:8080/web/viewer.html?file=浏览器中文件的地址
eg:localhost:8080/web/viewer.html?file=http://localhost:8080/pdf/demo/1.pdf
以下代码参考,主要就是路径,一定要对(根据自己的实际情况修改路径)
public String ckPdf(){
HttpServletRequest req =ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
// System.out.println(req.getRequestURL());
String path=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/";//项目地址
// System.out.println(path); //项目地址
final String pdfpath="D:/java/apache-tomcat-6.0.43/webapps/ycfc";//pdf绝对地址前面路径
ysxk = ysxkService.getById(ysxkId);
if(ysxk.getPdfurl()==null){
return null;
}
File file = new File(ysxk.getPdfurl());
// 取得文件名。
String filepath = file.getAbsolutePath();//得到pdf绝对路径
// System.out.println("filepath:"+" "+filepath);
filepath= filepath.replace("\\","/");//替换斜杠
String htpdfpath=filepath.substring(pdfpath.length());//截取后面内容,去除pdf绝对路径前面地址
// System.out.println(filepath);
String ckpdfpath=path+htpdfpath;//合成服务器pdf路径
// return "redirect:"+path+"/pdf/web/viewer.html?file="+ckpdfpath;
try {
res.sendRedirect(path+"pdf/web/viewer.html?file="+ckpdfpath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}