简体   繁体   中英

How to download the PDF in Jquery ajax call using java

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.

Downloading files via AJAX isn't really a logical thing to do. When you make an AJAX call, the data returned from the server is returned into your page's JavaScript code (in the response callback value), rather than being returned to the browser itself to decide what to do. Therefore the browser has no way to initiate a download, because the browser is not directly in control of the response - your JavaScript code is in control instead.

As you've indicated in your comment below the question, there are workarounds you can use, but really the best approach is simply to use a regular non-AJAX request to download

For instance you could replace your jQuery code with something like

$(document).on('click', '.orderView', function(event){
    orderId = $(this).attr('data');
    window.open('../service/purchase/generateInventoryPurchasePdf/'+orderId);
});

This will download the document from a new tab without navigating away from the current page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM