我尝试使用jsp代码打开itext创建的pdf文件,但没有打开有效的pdf文件。
BTW,如果我在生成的路径中打开pdf,那么它是有效的生成pdf。
<%
//code to generate pdf on file location.
String pdfurl = filePDF.getAbsolutePath();
File pdf = null;
try {
System.out.println("pdfurl : " + pdfurl);
response.setCharacterEncoding("utf-8");
pdf = new File(pdfurl);
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Disposition", "inline;filename=checklist.pdf");
response.setHeader("Accept-Ranges", "bytes");
response.setContentLength((int) pdf.length());
OutputStream sos = response.getOutputStream();
FileInputStream input = new FileInputStream(pdf);
BufferedInputStream buf = new BufferedInputStream(input);
int readBytes = 0;
while ((readBytes = buf.read()) != -1) {
sos.write(readBytes);
}
System.out.println("Finished writing bytes to output stream.");
sos.flush();
sos.close();
input.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (null != pdf && pdf.exists() && !pdf.isDirectory()) {
try {
pdf.delete();
System.out.println("Deleted file from " + pdfurl + " successfully");
} catch (Exception ex) {
System.out.println("Error while deleting pdf from : " + pdfurl);
}
}
}
%>
和ajax调用的angularJS代码:
pfqa.createDocument = function(action,data){
$("body").addClass("loading");
var deferred = $q.defer();
var paramJsonObj= {
'userId' : userId,
};
var data = angular.copy(paramJsonObj);
data = angular.toJson(data);
$http({
url : 'services/downloadPDF.jsp',
dataType: 'json',
method : 'POST',
headers : {
'Content-type' : 'application/json',
},
data: {data: paramJsonObj},
responseType : 'arraybuffer'
}).success(function(data, status, headers, config) {
var file = new Blob([ data ], {
type : 'application/json'
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'checklist.pdf';
document.body.appendChild(a);
a.click();
}).error(function(data, status, headers, config) {
});
$("body").removeClass("loading");
}
请指导我在这里缺少的东西。
答案 0 :(得分:1)
你在这里缺少的是:
使用: application / pdf 而不是 application / json
$http({
url : 'services/downloadPDF.jsp',
dataType: 'json',
method : 'POST',
headers : {
'Content-type' : 'application/pdf',
},
data: {data: paramJsonObj},
responseType : 'arraybuffer'
}).success(function(data, status, headers, config) {
var file = new Blob([ data ], {
type : 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'checklist.pdf';
document.body.appendChild(a);
a.click();
}).error(function(err) {
console.log(err);
});
那就是!!!