Marc Rasmussen
Marc Rasmussen

Reputation: 20545

pass HTML to phantom and render it to PDF

Normally in phantom you would be able to do something like this:

phantom = require('phantom')


phantom.create(function(ph){
  ph.createPage(function(page) {
    page.open("http://www.google.com", function(status) {
      page.render('google.pdf', function(){

        console.log('Page Rendered');
        ph.exit();

      });
    });
  });
});

However instead of loading a webpage i already have some html i want to pass and render as a PDF.

How would i be able to just pass it HTML and convert it to PDF and is PhantomJs the right appraoch for this or is ffmpeg a better approach and if so how do i use ffmpeg?

Upvotes: 1

Views: 2142

Answers (2)

sultan
sultan

Reputation: 4729

Phantom is no longer supported. I suggest to use puppeteer from the Chrome DevTools team. The code is much cleaner and readable:

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent(`<p>Hello world!</p>);
  // alternatively it can be fetched from web
  // await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});
  await page.pdf({path: 'hn.pdf', format: 'A4'});
  await browser.close();
})();

Upvotes: 0

pcwizz
pcwizz

Reputation: 142

You can set the content property of the page.

phantom = require('phantom')
phantom.create(function(ph){
    ph.createPage(function(page) {
        page.content = "Some html"//Set your html here
        page.render('google.pdf', function(){
            console.log('Page Rendered');
            ph.exit();
        });
    });
});

Upvotes: 2

Related Questions