0

Recently I'm working on a function which involve html template.

What this function does is to generate a dynamic template, and convert it into an image. As my understanding and what I R&D so far, it require to be a read stream before it able to convert into an image file.

So far, i manage to do it like this

fs.writeFile('sample.html', '<html>...</html>', function(err){
    fs.createReadStream('sample.html')
      .pipe(convert()) //function from html-convert npm package
      .pipe(fs.createWriteStream('out.png'))
});

Is there anyway to do this other than create a new file just for converting it to image?

Any help to this will be appreciated. Thanks.

Dean
  • 668
  • 12
  • 32
  • By converting to to image, do you mean the raw html code or the rendered html? I mean, What do you want to convert into image, just what you wrote or the rendered html? – Faisal Umair Oct 25 '17 at 06:04
  • yup it have to be displaying the rendered html... taking example of `
    Hello world
    ` my image will be an empty image with Hello world text on it.
    – Dean Oct 25 '17 at 06:08
  • I think node-webshot is your best friend, I tried it and works well. Posted as a answer. – Faisal Umair Oct 25 '17 at 06:26

2 Answers2

1

answer taken from How to create streams from string in Node.Js?

var Readable = require('stream').Readable;
var s = new Readable();
s.push('<html>...</html>');
s.push(null)
.pipe(convert()) //function from html-convert npm package
.pipe(fs.createWriteStream('out.png'))
});
Holger Will
  • 7,228
  • 1
  • 31
  • 39
1

Use node-webshot https://github.com/brenden/node-webshot

var webshot = require('webshot');

webshot('<html><body>Hello World</body></html>', 'hello_world.png', {siteType:'html'}, function(err) {

});

UPDATE

If you want the screenshot of rendered html as base64 you can do

var renderStream = webshot('<html><body>Hello World</body></html>', {siteType:'html'});

renderStream.on('data', function(data) {
  console.log(data.toString('base64'));
});
Faisal Umair
  • 381
  • 2
  • 5
  • this work well. thanks. one extra question. If I want base64 string of the image instead of write into a file, is that possible with this plugin – Dean Oct 25 '17 at 07:34
  • 1
    Try this, var renderStream = webshot('Hello World', {siteType:'html'}); renderStream.on('data', function(data) { console.log(data.toString('base64')); }); – Faisal Umair Oct 25 '17 at 08:43
  • No issues buddy, glad I could help :) – Faisal Umair Oct 25 '17 at 08:48