最近在项目中用到PDFJS查看浏览PDF文件,简单记下用法
jsp页面添加:<iframe src="js/pdfjs/web/viewer.html" width="100%" height="350px" id="Iframe"></iframe>
1、对于站点内路径直接赋值文件路径给SRCURL即可,不需要在后台去转换 ,对于跨域和用本地实际路径的文件加载可以把文件地址传到后台转成文件流加载,实际项目是从FTP下载文件得到的文件流 ,在这downloadFilePdf 只记了个简化版生成文件流
js
var pathName=window.document.location.pathname;
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
var filePath = $("#filesrc").textbox("getValue");
if (filePath!=''){
var srcurl=encodeURIComponent(projectName+"/downloadFilePdf.do?filePath="+filePath);
$("#Iframe").attr("src","js/pdfjs/web/viewer.html?file="+srcurl+"");
}
conroller 后台得到文件流
@RequestMapping(value = "/downloadFilePdf.do")
public void downloadFilePdf(@RequestParam("filePath")String filePath,HttpServletRequest request, HttpServletResponse response) {
try {
String filename = filePath.substring(filePath.lastIndexOf('/')+1);
response.setHeader("Content-Type","application/pdf");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Content-Disposition", "attachment;filename="+filename);
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
ByteArrayOutputStream returnStream = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
int sum = 0;
while ((len = inputStream.read(data))!= -1) {
returnStream .write(data, 0, len);
sum = len + sum;
}
byte[] returnBytes= returnStream .toByteArray();
response.getOutputStream().write(returnBytes);
} catch (Exception e) {
e.printStackTrace();
}
}
2、选择文件加载浏览可以用以下方式得到文件的blob url 地址
jsp: <label id="lblPdf">选择文件:</label> <input id="tbPdf" style="width: 200px" runat="server" name="PdfFile" type="file" οnchange="javascript:openPDF
(this);"/>
js:function openPDF(file){
if(!file.files||!file.files[0]){
return;
}
var f = file.files[0];
var filePath = null ;
if (window.createObjectURL!=undefined) { // basic
filePath = window.createObjectURL(f) ;
}else if (window.webkitURL!=undefined) { // webkit or chrome
filePath = window.webkitURL.createObjectURL(f) ;
}else if (window.URL!=undefined) { // mozilla(firefox)
filePath = window.URL.createObjectURL(f) ;
}
$("#Iframe").attr("src","js/pdfjs/web/viewer.html?file="+filePath +"");
}