Print Modal with CSS style

Asked

Viewed 80 times

0

I am trying to print a css style modal using the function below:

Content of the modal:

<div class="modal fade" id="infoModal">

   <!--Aqui vai o conteúdo do modal-->

   <div class="row no-print"><!-- Botão que chama a função -->

       <div class="col-12">

          <a onClick="imprimeModal()" target="_blank" class="btn btn-warning"><i class="fas fa-print"></i> Imprimir</a>
                                             
       </div>

    </div>

</div>

Function:

function imprimeModal(){

        var conteudo = document.getElementById('infoModal').innerHTML,
        tela_impressao = window.open('about:blank');
        tela_impressao.document.write('<!DOCTYPE html>');
        tela_impressao.document.write('<html lang="pt-br">');
        tela_impressao.document.write('<head><title>Teste</title>');        
        tela_impressao.document.write('<link href="../css/print.css" rel="stylesheet">');  
        tela_impressao.document.write('</head><body>');    
        tela_impressao.document.write(conteudo);
        tela_impressao.document.write('</body>');
        tela_impressao.window.print();
        tela_impressao.window.close();

    }

When I click the print button the first time generates the file unstyled CSS, but when I click a second time it generates the file CSS-style. If I close the modal and open again the same thing happens... Someone can tell me if I’m doing something wrong?

1 answer

0

You may be using the solution below, you can do the printing without losing CSS. If the site is for mobile access remove the following line from the script. // Remove once printed div $print.remove();

function imprimir(selector) {
  var $print = $(selector)
    .clone()
    .addClass('print')
    .prependTo('body');

  // Pausa JS executado
  window.print();

  // Remover div uma vez impresso
  $print.remove();
}
  @media print and (color) {
    @page {
      margin: 5mm;
      size: A4 portrait;
    }

    * {
      overflow: visible !important;
      -webkit-print-color-adjust: exact !important;
      print-color-adjust: exact !important;
      margin: 0 !important;
      padding: 0 !important;
      color: #212121 !important;
      visibility: hidden;
    }
    

    html,
    body {
      margin: 0 !important;
      padding: 0 !important;
    }
<div id="nomeModal">


</div>                


<button type="button" onClick="imprimir(nomeModal)">
                 Imprimir
                </button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.