PDFObject is not showing correctly in the browser

1.5k views Asked by At

I'm trying to render a embed pdf file using PDFObject. In the backend I send the pdf as follows

fs.readFile(uploadFileFd, function (err,data){
    res.contentType("application/pdf");
    res.send(data);
 });

After that I'm get the response in the front as follows

$.get("/loadDocument",function(data){
    PDFObject.embed(data,"#test");
  });

And I'm getting the following result image with the render in the browser of the pdf

Do you know how to fix that?

2

There are 2 answers

0
dilver On BEST ANSWER

I found that the problem was the encoding of the pdf file, so I encoded the file as base64 in the backend using 'base64-stream':

      var readStream = fs.createReadStream(uploadFileFd);

      // This will wait until we know the readable stream is actually valid before piping
      readStream.on('open', function () {
        // This just pipes the read stream to the response object (which goes to the client)
        readStream.pipe(new Base64Encode()).pipe(res);
      });
      // This catches any errors that happen while creating the readable stream (usually invalid names)
      readStream.on('error', function(err) {
        res.end(err);
      });

After that I use a embed tag to show the pdf:

var newElement = "<embed src=data:application/pdf;base64,"+data+" id='pdf' width='100%' height='1200'>";
1
Sunny Kumar On

It seems it's coming in binary format so you need to convert that to pdf again for rendering on the browser.

var request = new XMLHttpRequest();
request.open("GET", "/path/to/pdf", true); 
request.responseType = "blob";
request.onload = function (e) {
    if (this.status === 200) {
        // `blob` response
        console.log(this.response);
        // create `objectURL` of `this.response` : `.pdf` as `Blob`
        var file = window.URL.createObjectURL(this.response);
        var a = document.createElement("a");
        a.href = file;
        a.download = this.response.name || "detailPDF";
        document.body.appendChild(a);
        a.click();
        // remove `a` following `Save As` dialog, 
        // `window` regains `focus`
        window.onfocus = function () {                     
          document.body.removeChild(a)
        }
    };
};
request.send();

Please try the above.