JSFiddle - React, Tailwind, and code Playground

by Tobias Mesquita

HTML

Insira um trecho de HTML dentro do input abaixo:
<textarea id="taRawHtml">
    <h1>Hello Wolrd</h1>
</textarea>
<input id="btImprimir" type="button" value="Imprimir" />

CSS

html, body, div, input, textarea {
    box-sizing: border-box;
}
html, body {
    width: 100%;
    height: 100%;
    padding: 0px;
    margin: 0px;    
}

body {
    padding: 5px;
}

textarea {
    width: 100%;
    height: 240px;
}

JavaScript

var taRawHtml = document.getElementById("taRawHtml");
var btImprimir = document.getElementById("btImprimir");

btImprimir.addEventListener("click", function (event) {
    var html = taRawHtml.value.trim();
    if (html) {       
        var blob = new Blob([html], { type: "text/html" });        
        var iFrame = document.createElement("iframe");
        iFrame.addEventListener("load", function () { 
            iFrame.contentWindow.focus();
            iFrame.contentWindow.print();
            window.setTimeout(function () {
                document.body.removeChild(iFrame);
                URL.revokeObjectURL(iFrame.src);
            }, 0);
        });        
        iFrame.style.display = "none";
        iFrame.src = URL.createObjectURL(blob);
        document.body.appendChild(iFrame);
    }
});