javascripthtmlsails.jspdfobject

PDFObject is not showing correctly in the browser


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?


Solution

  • 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'>";