0

I am trying to generate simple PDF file using below code but failing with error : "Failed to load PDF document":

var downloadLink      = document.createElement('a');
downloadLink.target   = '_blank';
downloadLink.download = 'name_to_give_saved_file.pdf';

// convert downloaded data to a Blob
var blob = new Blob(['downloadedFile'], { type: 'application/pdf' });

// create an object URL from the Blob
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);

// set object URL as the anchor's href
downloadLink.href = downloadUrl;

// append the anchor to document body
document.body.append(downloadLink);

// fire a click event on the anchor
downloadLink.click();

Tried to follow many existing answers(e.g. How to build PDF file from binary string returned from a web-service using javascript) but did not get any solution yet. Please help. Thanks in advance :)

Jyoti Duhan
  • 988
  • 1
  • 16
  • 26
  • That seems to work for me. (and the downloaded file contains the content `downloadedFile`) – user202729 Jan 24 '18 at 11:15
  • But the binary `downloadedFile` (14 bytes) is not a valid PDF document. So of course the browser can't load it. – user202729 Jan 24 '18 at 11:17
  • 1
    you need to use some library to create a PDF file. WHat you are doing is just renaming it to .pdf but the document is not an actual pdf file. try using library like jsPDF – Abhishek Anand Jan 24 '18 at 11:23
  • #user202729 : how it worked for u? – Jyoti Duhan Jan 24 '18 at 11:24
  • The file contains the text "downloadedFile" (14 bytes). So it is doing what the code is telling it to do, hence it works. Also use @, not # to reply on Stack Exchange. – user202729 Jan 24 '18 at 11:29

1 Answers1

-4

Figured this out. The issue was that we need to pass a valid

pdf(datatype/contenttype - binary) to URL.createObjectURL(blob).

At line 6 of the code mentioned in the question, change

var downloadUrl = URL.createObjectURL(blob);

to

var downloadUrl = URL.createObjectURL(binary);

Thanks

Jyoti Duhan
  • 988
  • 1
  • 16
  • 26
  • 4
    Hello can you elaborate on this answer please? I am running into the same problem and I don't know how to implement your fix. – SamuelB Jul 16 '19 at 15:00
  • The explanation is simple :). If you got through the code in question here, at line 6 you need to change var downloadUrl = URL.createObjectURL(blob); to var downloadUrl = URL.createObjectURL(binary); – Jyoti Duhan May 19 '21 at 05:48
  • 1
    I am fascinated that somehow this was the answer for this person: Change the name of the variable "blob" to the undefined variable "binary". I also love that they felt there was no further explanation required here. lol. – Momus Sep 28 '22 at 16:28