0

My code is not downloading the pdf unless i install internet download manager

function downloadPdfDocument(bytes){
    $.post("/pdf/" + bytes ).done(function (data) {
    }).fail(function() {
        $("#cd-errors").show();
        $("#cd-errors").html("PDF file could not be downloaded");
    });
}
 @PostMapping("/pdf/{policyNumber}")
    public ResponseEntity<byte[]>  downloadPdf( @PathVariable("policyNumber") String policyNumber) throws IOException, JRException {

       //code to prepare parameters 

        byte[] contents  = jasperUtils.generateStatement(null, null, null, transactionHistories, statementInformations);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        headers.add("content-disposition", "inline;filename=" + policyNumber + ".pdf");
        headers.setContentDispositionFormData(policyNumber + ".pdf", policyNumber + ".pdf");
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
        return response;

  }
Musa
  • 96,336
  • 17
  • 118
  • 137
Thakhani Tharage
  • 1,288
  • 16
  • 19
  • @Musa you clearly do understand what my question is all about, you went north when I am going south. Let me simplify maybe it will help. I am building a PDF document from the byte array. I know the PDF works because I can write to disk or attache to an email, however, I need it to be downloadable from the browser and with the code above is not happening. Please guide on what I am doing wrong. – Thakhani Tharage Nov 04 '18 at 16:27
  • You should be going north too, did you read the question and answers in the link? – Musa Nov 05 '18 at 02:48
  • Yes I did and unfortunately, I am not winning. The pdf generated is empty meaning the code disregard my content. – Thakhani Tharage Nov 05 '18 at 05:49

1 Answers1

0

I ended up not using Ajax. Below code worked form me

function downloadPdfDocument(fileName){

var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";

req.onload = function (event) {

    var blob = req.response;

    //for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    }
};

req.send();

}

Thakhani Tharage
  • 1,288
  • 16
  • 19