问题
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