Print another page with javascript

1

I have a system which shows the result of a query. On this page you have the print button, but I need to make clicking the print button print another formatted page without having to open it for it, or if it is the case, do not even download, open and close automatically. I have the following code on the main page (index.php):

    <script>
               $(function(){ 
                   //evnto que deve carregar a janela a ser impressa 
                   $('#imprimir').click(function(){ 
                      newWindow = window.open('imprimir.php'); 
                       //imprime e fecha a nova janela quando estiver carregada 
                       $(newWindow).ready(function() { 
                           newWindow.print(); 
                           newWindow.close(); 
                       }); 
                   }); 
               }); 
            </script>
<a href="#" style="color: #666666; font-weight: bold" id="imprimir"><i class="fa fa-print"></i> Imprimir Orçamento</a>
    
asked by anonymous 14.10.2015 / 16:22

1 answer

1

look, in this case you'd better create an iFrame for the desired content, until the window.open can be blocked by the Browser.

var iFrame = document.createElement("iframe");
iFrame.addEventListener("load", function () { 
  iFrame.contentWindow.focus();
  iFrame.contentWindow.print();
  window.setTimeout(function () {
    document.body.removeChild(iFrame);
  }, 0);
});        
iFrame.style.display = "none";
iFrame.src = "imprimir.php";
document.body.appendChild(iFrame);

Below is a functional example with an excerpt of HTML that is entered by the user.

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);
  }
});
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;
}
Insira um trecho de HTML dentro do input abaixo:
<textarea id="taRawHtml">
  <h1>Hello Wolrd</h1>
</textarea>
<input id="btImprimir" type="button" value="Imprimir" />

Unfortunately the above example will not run here in the OS because of a policy applied to the Snippet iFrame, but you can see it in action at the following JSFiddle

    
14.10.2015 / 18:58