Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer JS generate PDF from selector

I'm familiarizing myself with Puppeteer to use in a Vue.js app but I can't figure out how to generate a PDF based on specific element on the page. I can successfully create a PDF based on the full page, but that's not ideal. Is there a method or class I missed that can allow this? I couldn't find a chainable page function to filter by selector(s) like so:

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://what.a.fancy/website', {waitUntil: 'networkidle2'});
    await page.$('.just-this-html').pdf(options);

I did see there's a page.$(selector) function but I'm not sure how to chain that with a .then() call that could access the returned HTML to a PDF.

Thanks!

like image 664
slowFooMovement Avatar asked Jun 28 '18 21:06

slowFooMovement


1 Answers

Try code this. await page.setContent() page.setContent

Example

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.google.com/', {waitUntil: 'networkidle2'});
const dom = await page.$eval('div.jsb', (element) => {
     return element.innerHTML
}) // Get DOM HTML
await page.setContent(dom)   // HTML markup to assign to the page for generate pdf
await page.pdf(options)
like image 54
aofdev Avatar answered Nov 10 '22 13:11

aofdev