Dom-to-image: Printing node not currently attached to DOM

Created on 5 May 2016  路  9Comments  路  Source: tsayen/dom-to-image

I have got your excellent module working when I am printing an element found by its Id (as per your documentation) however I have a requirement to print HTML provided to me by an external service.

My attempt currently looks like this:

    var fromHtml = function (html) {
        var promise = $q(function(resolve, reject) {
            var node = document.createElement('div');
            node.innerHTML = html;

            domtoimage.toPng(node)
            .then(function (dataUrl) {
                // Trim meta information
                var trimmed = dataUrl.replace('data:image/png;base64,', '');
                resolve(trimmed);
            })
            .catch(function (e) {
                reject('Error converting HTML to canvas for printing: ' + e);
            });
        });

        return promise;
    };

The behaviour I am seeing is... nothing happens; it doesn't even hit my "catch".

I've had a look through the code and can't see anything obvious requiring the html passed into the .toPng(...) function be attached to the DOM however if I embed the HTML in my DOM and pass an Id as your docs it does work?

Have you got any ideas on this? I cannot easily embed the HTML into the DOM for every case.

wontfix

Most helpful comment

I found a solution to this problem. Here is my code in-case anyone else wants to do this:

// The element being rendered has to be added to the document for DomToImage to work.
// We don't want to show it on-screen so we position it off-screen.
let position = exportElement.style.position;
let left = exportElement.style.left;
exportElement.style.position = 'absolute';
exportElement.style.left = '-9999px';
document.body.appendChild(exportElement);

let blob = await DomToImage.toBlob(exportElement, {
  style: {
    // Revert the off-screen positioning
    position: position,
    left: left
  }
});

document.body.removeChild(exportElement);

I needed this as we wanted to modify the HTML of the image differently to how the built in filter works. I cloned the element, made my modifications and then passed the clone to DomToImage.

All 9 comments

Hi, sorry for late reply. Could you please put together a jsfiddle?

Hi, I have the same problem.

When I try to render a node not attached to any element of the tree I get a generic error in the catch clause.

If I try to attach the node on the DOM tree, but I set the visibility to 'hidden' the resulting image is empty. Is there a way to just render an html parsed code into a png image?

Thanks! Great job by the way!

Hi. Actually I've never tried to render such a node. The general use case I've wrote this ilb for is that you have a visible part of the page you want to export as image.

It might be that the way this lib works (it gets calculated styles for all the children of the node recursively) is relying on the fact that the node got rendered by the browser at least once. @croll83 I think when you say visibility: hidden on the node that you want to render, then this property (like all calculated styles) is applied to this node when rendering. Maybe you can try to turn this off by using style option, like domtoimage.toPng(node, {style: {visibility: visible}}), but I'm not sure whether this will work.

Rendering HTML string to image would be a great feature, I wonder if it is possible to add with the current implementation, I'll have to think about it.

Already tested with the option but it still don't work. I solved by appending the child to an element of the page, calling the .toBlob method on that node and removing the child on the callback. This will show the element for less than a second and remove it. This is not very elegant, but it's the max I was able to do.

I tryied to debug the code but I lost in the Promises so I was not able to find the error source. it's a very generic error. If I could help you contact me and tell me how :)

BTW I have another problem... I'm not able to apply font on the image. Even if I define standard font like verdana in the style element of the main div it's not applied. Any idea about?

this is the code i'm using:

var htmlCard = '

SOME CONTENT HERE
';

var cardDiv = document.createElement('div');

cardDiv.innerHTML = htmlCard;

document.getElementByID('canvas').appendChild(cardDiv);

domtoimage.toBlob(canvas, {
style: {
'font-family': 'Verdana'
}
})
.then(function (blob) {
window.saveAs(blob, 'card.png');
canvas.removeChild(cardDiv)
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});

html child definition removed for html tags...
var htmlCard = '<div style="width:660px; color: #000000; background-color: white;line-height:115%; @font-face{font-family:\'Raleway\';font-style:normal;font-weight:400;src:local(\'Raleway\'),local(\'Raleway-Regular\'),url(https://fonts.gstatic.com/s/raleway/v11/yQiAaD56cjx1AooMTSghGfY6323mHUZFJMgTvxaG2iE.woff2) format(\'woff2\');unicode-range:U+0100-024F,U+1E00-1EFF,U+20A0-20AB,U+20AD-20CF,U+2C60-2C7F,U+A720-A7FF;}; @font-face{font-family:\'Raleway\';font-style:normal;font-weight:400;src:local(\'Raleway\'),local(\'Raleway-Regular\'),url(https://fonts.gstatic.com/s/raleway/v11/0dTEPzkLWceF7z0koJaX1A.woff2)format(\'woff2\');unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02C6,U+02DA,U+02DC,U+2000-206F,U+2074,U+20AC,U+2212,U+2215,U+E0FF,U+EFFD,U+F000;}; font-family: \'Raleway\'"><div style="width:660px; text-align: center; margin: 0px 30px; padding-bottom: 0px">SOME CONTENT HERE</div>';

probably can't be done with current impl

I found a solution to this problem. Here is my code in-case anyone else wants to do this:

// The element being rendered has to be added to the document for DomToImage to work.
// We don't want to show it on-screen so we position it off-screen.
let position = exportElement.style.position;
let left = exportElement.style.left;
exportElement.style.position = 'absolute';
exportElement.style.left = '-9999px';
document.body.appendChild(exportElement);

let blob = await DomToImage.toBlob(exportElement, {
  style: {
    // Revert the off-screen positioning
    position: position,
    left: left
  }
});

document.body.removeChild(exportElement);

I needed this as we wanted to modify the HTML of the image differently to how the built in filter works. I cloned the element, made my modifications and then passed the clone to DomToImage.

I found a solution to this problem. Here is my code in-case anyone else wants to do this:

// The element being rendered has to be added to the document for DomToImage to work.
// We don't want to show it on-screen so we position it off-screen.
let position = exportElement.style.position;
let left = exportElement.style.left;
exportElement.style.position = 'absolute';
exportElement.style.left = '-9999px';
document.body.appendChild(exportElement);

let blob = await DomToImage.toBlob(exportElement, {
  style: {
    // Revert the off-screen positioning
    position: position,
    left: left
  }
});

document.body.removeChild(exportElement);

I needed this as we wanted to modify the HTML of the image differently to how the built in filter works. I cloned the element, made my modifications and then passed the clone to DomToImage.

Actually you can even elegantly improve it by creating a parent that is already offset on document creation, append the exportElement to the hidden parent then do your DomToImage, this way you will write less code offsetting and resetting the exportElement

I found a solution to this problem. Here is my code in-case anyone else wants to do this:

// The element being rendered has to be added to the document for DomToImage to work.
// We don't want to show it on-screen so we position it off-screen.
let position = exportElement.style.position;
let left = exportElement.style.left;
exportElement.style.position = 'absolute';
exportElement.style.left = '-9999px';
document.body.appendChild(exportElement);

let blob = await DomToImage.toBlob(exportElement, {
  style: {
    // Revert the off-screen positioning
    position: position,
    left: left
  }
});

document.body.removeChild(exportElement);

I needed this as we wanted to modify the HTML of the image differently to how the built in filter works. I cloned the element, made my modifications and then passed the clone to DomToImage.

I guess things must've changed because after setting to absolute positioning, my image renders transparency.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AvanishKumar008 picture AvanishKumar008  路  8Comments

AbuSufyan picture AbuSufyan  路  7Comments

distroyq picture distroyq  路  6Comments

Pistil-Studio picture Pistil-Studio  路  6Comments

DanielZambranoC picture DanielZambranoC  路  5Comments