Search code examples
javascripthtml2canvasjspdf

Changing html2canvas to accept display as none


I am using jsPDF which make use of html2canvas. Here is an example of it.

Based on this answer, I downloaded html2canvas and started using it locally to make this change as suggested, because the option of setting the colour as other answers proposed didn't worked for me.

Also, I notice other requirement I have which is different of what html2canvas delivers by default. I need to be able generate a PDF file even if the display is set to none.

Note on the example I gave, the option HTML Renderer (early stages) works with display none, but implements a poor render. On the other hand, addHTML() which is what I am using now, renders the page as it is, but this implies to render only what is visible.

This is the default method of html2canvas to decide what to consider as Visible.

function isElementVisible(element) {
        return (getCSS(element, 'display') !== "none" &&
                getCSS(element, 'visibility') !== "hidden" &&
                !element.hasAttribute("data-html2canvas-ignore"));
}

I commented the line: getCSS(element, 'visibility') !== "hidden", and it enabled me to create a PDF even if visibility: hidden. However the samething is not true for display: none, even if the method always return TRUE.

How to implement it?


Solution

  • A node with display: none can't get a DOMRect calculated for it, as it does not have one within the DOM (as it is display: none).

    If you want to render display: none content, you'll need to make the display of the node something else prior to rendering.

    Starting with html2canvas 0.5.0, you can provide an onclone option to html2canvas which is a callback that returns the cloned document object, where you can go and modify the DOM as you see fit prior to rendering it, without affecting the original document.