Stack Exchange
JAX-RS | Download PDF from Base64 encoded data
Folks,
I have a REST controller that calls a service to get a BASE 64 encoded string that represents a PDF. I'm calling my REST endpoint through an AJAX call. I basically want the user to actually download a PDF file when they click on a link.
Here is the REST controller:
@GET
    @Path("/getinvoice/{invoiceid}.pdf")
    @Produces("application/pdf")
    @Consumes(MediaType.TEXT_HTML)
    public Response invoice(@PathParam("invoiceid") final String invoiceid) throws ShoppingCartException, UnexpectedErrorFault_Exception,
            MalformedQueryFault_Exception, InvalidQueryLocatorFault_Exception, LoginFault_Exception, IOException {


        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedBytes = decoder.decodeBuffer(aService.getInvoiceBody(invoiceid));
        ResponseBuilder response = Response.ok(new ByteArrayInputStream(decodedBytes));
        response.header("Content-Disposition", "attachment; filename=test.pdf");
        return response.build();
}

The service returns a BASE64 encoded string (representing a PDF) that I convert to a byte array (after some google search). I just want the user to see a file download popup with the name 'invoiceid}.pdf' when they click on the link. As of now the response is returned but nothing happens.
Would appreciate any pointers or help here..
Update: Just as a quick test, I disabled the Ajax call and directly called the REST endpoint from the . I was then able to successfully download the file. Perhaps due to some security reasons, this is not achievable through Ajax. 
Also, I'd like the users to see some kind a 'Please wait' message while this processing happens in the backend. I'd appreciate any inputs on that as well.

I don't really get the mentioning about the google search? If you want when someone searches your page, and they see the link in search results, you want to download the file without leaving the google search page, I have no idea how that would be done. If the link is on your page, all that is required is to have an <a href=""> to the resource. For an AJAX call, it's a bit more difficult, and you will need to know some Javacript to open the save as dialog. I personally, do not know how to do this with Javacript.

@peeskillet My apologies for not being very clear with my question. The part about google search can safely be ignored. It was just to convey that I read about some approaches to get this done and one of them suggested to convert the data to a byte array.

Have a look at this Q&A

Check Q & A posted by @peeskillet, you will require to use iframe to show download popup by browser. As your direct call to URL works fine then you can load the same URL in IFrame. As soon as your URL is hit in IFrame, browser will show popup message to save the file you don't need to show Please wait message as immediately the download will start.
