Search code examples
javascriptreactjsnpmhtml2canvas

Provided element is not within a Document - Reactjs


I am trying to send HTML invoices to users as Image.

For that purpose i am using html2canvas library, but it is continuously giving me error:

Provided element is not within a Document

Here is what i am trying to do in componentDidMount()

html2canvas(document.getElementById('invoice'), {
        logging: true,
        profile: true,
        useCORS: true}).then(function(canvas) {
    var data = canvas.toDataURL('image/jpeg', 0.9);
    var src = encodeURI(data);
    console.log(src);
});

And invoice element do exist in DOM.

What could be wrong?


Solution

  • Perhaps try to capture the element with refs.

    So your component will look like this:

    class Invoice extends React.Component {
        componentDidMount(){
            html2canvas(this.invoice, {
                    logging: true,
                    profile: true,
                    useCORS: true}).then(function(canvas) {
                var data = canvas.toDataURL('image/jpeg', 0.9);
                var src = encodeURI(data);
                console.log(src);
            });
        }
        render(){
            return <div ref={r => this.invoice = r}>....</div>
        }
    }