Is there a way to target a specific element using Puppeteer AND preserve the CSS when converting html to pdf?

Viewed 969

I'd like to convert some html to a pdf file. The problem is that I just need a part of a webpage and most certainly not all elements. So I was wondering if there is a way to target a single element with a specific id for example, so that only that element gets converted to a pdf?

I know I can do this for example:

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

However, using the code above won't preserve the CSS...

It is also not an option to use page.addStyleTag to add the css by hand, since the element I am trying to convert to a pdf has loads and loads of CSS styles already applied to it...

So the question remains, how can I convert a single element on a page using Puppeteer (or if you know of other ways / methods / libraries, then those are welcome too of course).

Grabzit for example allows to you to specify the targetElement in their options like so:

const options = {
   'targetElement': '#rightContent',
   'pagesize': 'A4',
}

Unfortunately, it does not give me consistent results.

1 Answers

I have had some success like this:

const myElement = await page.$('.my-el');
await page.evaluate(el => {
  el = el.cloneNode(true);

  document.body.innerHTML = `
    <div>
      ${el.outerHTML}
    </div>
  `;
}, myElement);
const pdf = await page.pdf(...)

However it is not working very well when the element I select contains Canvas elements.

(Code based on example here https://github.com/puppeteer/examples/blob/master/element-to-pdf.js)

Related