Freddy Freddy - 10 months ago 415
Javascript Question

AngularJS open PDF in new tab and change filename/url

In my AngularJS Website I want to load .pdf documents and show them in new browser tabs. The following code works, but some things bother me:

The createdObjectURL is set as the title of the document and browser tab. That means my documents are always titled as somthing like

which is not really decent. And the visible URL isn't good, too. Instead of
it would be better to have the URL I call in the service.js.

I tried to handle the filename in the HttpHeaders, but that has no effect at all :(

Another strange thing: if I do not specify the
{responseType: "arraybuffer"}
, the PDF-Title is displayed correctly. But there is no content, the document is empty.

Any help on how to change the filename and/or URL would be appreciated. Thank you.

JS Controller

DocumentService.getDocument().then(function(response) {
$, '_blank');

JS Service

return {
getDocument : function () {
return $http.get("document", {responseType: "arraybuffer"})
.then(function(response) {
var file = new Blob([], {type: "application/pdf"});
var fileURL = URL.createObjectURL(file);
return fileURL;

Spring MVC ReST-Service

@RequestMapping(value = "/document", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDocument(){
try {
File file = new File("C:\\pathToFile.pdf");
byte[] fileContent = new byte[(int) file.lenth()];

HttpHeaders heraders = new HttpHeaders();
String filename = "NameOfFile.pdf";
headers.setContentDispositionFormData(filename, filename); //doesn't change anything

fileContent = File.readAllBytes(file.toPath());

ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK);

return response;
} catch (FileNotFoundException e ) {
System.err.println("File not found " + e);
} catch (IOException e ) {
System.err.pringln("Error while reading file " + e);

Short version:
When a PDF file is loaded as a byte array and displayed it in a new browser tab with the AngularJS $window directive: Is there a good possibility to change the filename and URL?

Answer Source

Open a new tab with the url to the resource returning the byte-array! Something like:

$'localhost:xxx/api/document', '_blank');