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

Asked

Viewed 2,854 times

6

I make a requisition 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 java REST service?

2 answers

6


It is not feasible to use Ajax to display a PDF. What you need is just to 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 a suitable place on the current page src (URL) points to the service that returns the PDF via request GET.

Example:

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

If your system does not use traditional browsing between pages, don’t forget to remove the added element to free the allocated resources.

New window

Another simple option is to open the report in a new window, either through a link with target="blank" or via a popup via Javascript.

2

It’s simpler than it looks. I believe it should be a button click event, if yes, 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 will download instead of opening, because the server headers are already doing this.

  • reviving this post is that I can do this for unpublished files or that are not in my project folder in them are accessed via a URL

Browser other questions tagged

You are not signed in. Login or sign up in order to post.