I have an existing servlet which gives me a pdf byte array:
byte[] pdf = myService.getPdf(myArgs);
response.setContentType("application/pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentLength(pdf.length);
ServletOutputStream out = response.getOutputStream();
out.write(pdf);
out.flush();
out.close();
// for test: byte[] pdf
File testfile = new File("C:\\mytestpath\\mytest.pdf");
FileOutputStream fos = new FileOutputStream(testfile);
fos.write(pdf);
fos.flush();
fos.close();
I write in my servlet a test pdf file to check the return value of myService.getPdf(). The testfile is ok, I can open this valid file in acrobat reader.
And now my JQuery-JavaScript code:
function generatePDF(url) {
currentRequest = $.ajax({
url: url,
type: "GET",
success: function(data) {
var blob = new Blob([data], {type: 'application/pdf'});
var fileURL = window.URL.createObjectURL(blob);
window.open(fileURL, "_blank");
},
error: function() {
console.error("test in generatePDF error");
// use here other jquery mobile functions
}
});
}
I want to generate a PDF byte array in my servlet and show the PDF in a new browser tab. With my implementation a new browsesr tab is open (address line: blob:http%3A//localhost%3A8080/3fd5808b-758b-4076-94c9-af9884f631a3). But the PDF file is empty, the page size of the PDF file is ok. How can I solve this problem? I need a valid PDF with name myid.pdf in a new browser tab.
Thank's for yor hints, Thomas
You could just open your servlet URL in a new window. There is no need for AJAX call or JQuery.
In your servlet, you could add headers which hint the browser what file name to suggest to user if he chooses to save the file.
response.setHeader("Content-Disposition", "attachment;filename=" + pdfName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With