How to display a PDF in the browser with an ajax request?

6

I make a request like this:

$.ajax({type : 'GET', url : URL_APP_CONSULTA_BOLETO_DIVIDA_ATIVA + url});

I have a java method that returns something like this:

return (Response.ok(output).header("content-disposition", "attachment; filename = " + filename).type( "application/pdf").build());

If we look at http we have the following:

Request URL:http://xxxxx:8080/app/ConsultaDividaAtiva/boleto/100008621/3npm54
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:JSESSIONID=6EE1049F45C246F7AB91CD196BC6ADF5
Host:localhost:8080
Referer:http://localhost:8080/view-app/EmiteBoletoDividaAtiva.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)  Chrome/32.0.1700.107 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headersview source
content-disposition:attachment; filename = boleto_20022014115213.pdf
Content-Type:application/pdf
Date:Thu, 20 Feb 2014 14:52:13 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.4; JBoss-4.2.3.GA (build: SVNTag=JBoss_4_2_3_GA date=200807181417)/JBossWeb-2.0;

The question is: how to display / download the PDF returned by the REST service in java?

    
asked by anonymous 20.02.2014 / 16:00

2 answers

6

It is not feasible to use Ajax to display a PDF. What you need is to just open a new window or create a frame pointing to the URL that returns the PDF. The browser will automatically make a request GET .

Using iframe

A simple solution is to create a iframe in an appropriate location on the current page whose src (URL) points to the service that returns the PDF via GET request.

Example:

$(document.body).append(
    '<iframe src="http://www.forelise.com/media/for_elise_sheet_music.pdf">');

Ifyoursystemdoesnotusetraditionalcross-pagenavigation,besuretoremovetheaddedelementtoreleasetheallocatedresources.

Newwindow

Anothersimpleoptionistoopenthereportinanewwindow,eitherthroughalinkwithtarget="blank" or via a popup via Javascript.

    
20.02.2014 / 16:14
2

It's simpler than it looks. I think it should be a one-click event, if so, the code snippet that makes downloading the file can be a simple

location.href = "http://xxxxx:8080/app/ConsultaDividaAtiva/boleto/100008621/3npm54";

The browser will be directed to the file, but it will download rather than open because the server headers are already doing so.

    
27.02.2014 / 15:49