Trying to send a PDF from a servlet to the client. The client sends a POST request through AJAX, and the request is handled by the servlet to generate a PDF and sends the PDF as a response to the client.
I've tried the options posted here to no avail (getting empty/un-openable pdfs): Opening PDF String in new window with javascript
Any help would be apprecieated!
So far, I can only get a formatted PDF String printing in the browser console using this code:
Java Servlet:
response.setContentType("application/pdf");
response.setHeader("Content-disposition","attachment; filename=ProgressReport.pdf");
response.setContentLength((int) pdfFile.length());
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(pdfFile);
byte[] buffer = new byte[1024];
int length =0;
while ((length = in.read(buffer)) != -1){
out.write(buffer, 0, length);
System.out.println(buffer);
}
in.close();
out.flush();
JS
$.ajax({
url : "GenerateReport",
data : {
...
},
type : "POST",
success : function(result) {
console.log(result);
//window.open("data:application/pdf, " + encodeURI(result));
//download(result);
},
error : function(result) {
...
}
})
PDF String in Browser Console
%PDF-1.4 %����3 0 obj<</Filter/FlateDecode/Length 238>>streamx��QMO�@��x��(��D��!A�x�R��T�-�n��{�5LDB�e2�y�>2�l�Y$1�:a�i.�"�~f ...