Sails EJS-view after html-pdf usage does not render image

◇◆丶佛笑我妖孽 提交于 2019-12-12 04:28:25

问题


I need to be able to render html views (nothing new there) and to provide the same views as PDF file to the final user.

The first case works perfectly on my side : I managed to render a simple html5 document aswell as an image two times (the base64 version + the standard way).

Unfortunately, when I try to convert it to a PDF file thanks to html5-to-pdf or html-pdf, the non-base64 version of the <img> tag does not work and is signaled as a missing resource within the PDF File.

The code I'm using is the following :

Controller :

//res is the response parameter provided to the controller

var pdf = require('html-pdf');

var variables = {

};

ejs.renderFile('./views/samplepdf.ejs', variables, function(err, result) {
  // render on success
  if (result) {
    html = result;

    pdf.create(html).toStream(function(err, stream){
      res.contentType("application/pdf");
      stream.pipe(res);
    });

  }
  // render or error
  else {
    res.end('An error occurred');
    console.log(err);
  }
});

View :

<h2>Image</h2>
<img class="smaller" src="data:image/jpeg;base64,/validbase64ButIHadToSaveBecauseCharactersLimitExceeded" alt="Sample image" />
<img class="smaller" src="images/ymca.jpg" alt="Sample image #2" />

I've carefully read the Sails specification about Grunt tasks and assets management, therefore the given images/ymca.jpg does exist and can be access from the browser. I still do not know why does the PDF does not render it.


回答1:


all you have to do is use full path of image while render on pdf controller

var variables = {
  path: sails.config.appPath + 'assets/images/ymca.jpg'
};

view

<img class="smaller" src="<%= path %>" alt="Sample image #2" />

while render on pdf using html-pdf, it does not work with absolute path.



来源:https://stackoverflow.com/questions/41302988/sails-ejs-view-after-html-pdf-usage-does-not-render-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!