I created a service to download a PDF file.
On my server-side(Java) the PDF is generated successfully. But I am unable to download that on the UI side (Using Jquery Ajax call).
Could anyone please help me with this?
$(document).on('click', '.orderView', function(event){
    orderId = $(this).attr('data');
    $.ajax({
        type : 'GET',
        contentType : 'application/json',
        url : '../service/purchase/generateInventoryPurchasePdf/'+orderId,
        success : function(response) {
            console.log("Success");
        },
        error : function(response) {
            console.log("Error :" + response);
        }
    });
}); 
Java Code:
@RequestMapping(value = "/generateInventoryPurchasePdf/{purchaseId}", method = RequestMethod.GET)
public ResponseEntity<ByteArrayResource> generateInventoryPurchasePdf(HttpServletResponse response,@PathVariable("purchaseId") Long purchaseId) throws Exception {
PurchaseOrder purchaseOrder = null;
    purchaseOrder = purchaseService.findByPurchaseOrderId(purchaseId);
    // generate the PDF
    Map<Object,Object> pdfMap = new HashMap<>();
    pdfMap.put("purchaseOrder", purchaseOrder);
    pdfMap.put("purchaseOrderDetail", purchaseOrder.getPurchaseOrderDetail());
    pdfMap.put("vendorName", purchaseOrder.getInvVendor().getName());
    pdfMap.put("vendorAddrs", purchaseOrder.getInvVendor().getVenAddress().get(0));
    File file = util.generatePdf("email/purchasepdf", pdfMap);
    MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, file.getName());
    System.out.println("fileName: " + file.getName());
    System.out.println("mediaType: " + mediaType);
    //Path path = Paths.get(file.getAbsolutePath() + "/" + file.getName());
    Path path = Paths.get(file.getAbsolutePath());
    byte[] data = Files.readAllBytes(path);
    ByteArrayResource resource = new ByteArrayResource(data);
    return ResponseEntity.ok()
            // Content-Disposition
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + path.getFileName().toString())
            // Content-Type
            .contentType(mediaType) //
            // Content-Lengh
            .contentLength(data.length) //
            .body(resource);
}
mediaUtil class:
public class MediaTypeUtils {
    public static MediaType getMediaTypeForFileName(ServletContext servletContext, String fileName) {
        // application/pdf
        // application/xml
        // image/gif, ...
        String mineType = servletContext.getMimeType(fileName);
        try {
            MediaType mediaType = MediaType.parseMediaType(mineType);
            return mediaType;
        } catch (Exception e) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }
}
PDF Generation code:
public File generatePdf(String templateName, Map<Object, Object> map) throws Exception {
    Assert.notNull(templateName, "The templateName can not be null");
    Context ctx = new Context();
    if (map != null) {
        Iterator<Entry<Object, Object>> itMap = map.entrySet().iterator();
        while (itMap.hasNext()) {
            Map.Entry<Object, Object> pair = itMap.next();
            ctx.setVariable(pair.getKey().toString(), pair.getValue());
        }
    }
    String processedHtml = templateEngine.process(templateName, ctx);
    FileOutputStream os = null;
    String fileName = "POLIST";
    try {
        final File outputFile = File.createTempFile(fileName, ".pdf",new File(servletContext.getRealPath("/")));
        outputFile.mkdir();
        os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(processedHtml);
        renderer.layout();
        renderer.createPDF(os, false);
        renderer.finishPDF();
        System.out.println("PDF created successfully");
        return outputFile;
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) { 
            }
        }
    }
}
I'm not getting any error, PDF generate successfully in the server side. But In UI side not working.
 
     
    