11

I'm new to angular js and I wish to open a PDF document in a new window of the browser after pressing a button.

I make a GET request with $http.get() at front end, at backend there is a Java rest service that respond to the GET and generates a PDF. I wish to open this PDF on the browser.

If is not possible to open the PDF in this way then at least open any PDF with AngularJs, how could I do this?

@GET
@Path("/printPdf")
public Response printService(){

//generates the pdf

File reportFile = new File(filePath);
String name = reportName + "." + "pdf";
ResponseBuilder response = Response.ok(new     TemporaryFileInputStream(reportFile));
response.header("Content-Disposition", "attachment; filename=" + name);
response.header("Content-Type", "application/pdf");
response.header("Access-Control-Expose-Headers", "x-filename");
response.header("x-filename", name);

return response.build();
}

this is what there is at backend to generate the response in the rest service.

DarkAngeL
  • 419
  • 2
  • 5
  • 17

2 Answers2

18

If you had something like this:

var myPdfUrl = 'something'
$http.get(myPdfUrl);

Do this instead:

var myPdfUrl = 'something'  
$window.open(myPdfUrl);

If instead you have something like this:

$http
    .get(generatePdfUrl)
    .then(function(data){
        //data is link to pdf
    });     

Do this:

$http
    .get(generatePdfUrl)
    .then(function(data){
        //data is link to pdf
        $window.open(data);
    });         
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
  • 1
    I've tried your solution but its not working seems I'm doing something wrong at backend in the rest service, i just edited and posted the code of it. Is there something wrong? – DarkAngeL May 05 '15 at 13:59
  • 1
    Thanks Mathew Berg , I made it work changing this line of code response.header("Content-Disposition", "attachment; filename=" + name) to response.header("Content-Disposition", "inline; filename=" + name) because it was asking me to download instead of open the file in a new window. – DarkAngeL May 05 '15 at 15:07
  • Thanks but it's actually ` window.open(data);` – Sboniso Marcus Nzimande Apr 15 '16 at 11:52
  • @SbonisoMarcusNzimande This is angular, you inject the $window so you can mock tests. – Mathew Berg Apr 15 '16 at 12:05
17

Maybe this can help,in the case of you have something like this :

$http.get('generatePdfUrl')
  .then(function (data) {     // data is your url
      var file = new Blob([data], {type: 'application/pdf'});
      var fileURL = URL.createObjectURL(file);
  });

Then use your service in controller and do

$window.open(fileURL);
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
carton
  • 1,168
  • 9
  • 17