Print div with styles in JS

1

Good afternoon friends of the community, today I come with a question that I hope you can help me solve, it turns out that I want to print a div with JS but when sending the parameters in the function the styles do not respect them and the file is done a disaster. I want the file that will be printed to open in another tab and keep the styles. I have only managed to make the document open in another tab but it does not maintain the styles, someone help me please, I will thank you very much. This is how the website looks and how the document looks:

<script type="text/javascript">

        function printDiv() {
          var objeto=document.getElementById('imprimir');  //obtenemos el objeto a imprimir
          var ventana=window.open('','_blank');  //abrimos una ventana vacía nueva
          ventana.document.write(objeto.innerHTML);  //imprimimos el HTML del objeto en la nueva ventana
          ventana.document.close();  //cerramos el documento
          ventana.print();  //imprimimos la ventana
          ventana.close();  //cerramos la ventana
        }
    </script>

This is the div I want to Print

<div class="imprimir" id="imprimir">
                    <div class="titulo">HOJA DE SERVICIOS INFORMATICOS</div>
                    <table>
                         <tr>
                            <th>
                                <font style=" text-decoration: underline;">DATOS DEL USUARIO</font><br>
                                <strong>Usuario: </strong><br>
                                <strong>Nombre del Responsable: </strong><br>
                                <strong>Proveedor del Servicio: </strong><br>
                                <strong>Área Solicitante: </strong><br>
                            </th>
                            <th>
                                <font style=" text-decoration: underline;">DATOS DEL REPORTE</font><br>
                                <strong>Número de Orden: </strong><br>
                                <strong>Fecha de Registro: </strong><br>
                                <strong>Hora de Registro: </strong><br>
                                <strong>Reportó: </strong><br>
                            </th>
                         </tr>                              
                        <tr>
                            <th>

                                <font style=" text-decoration: underline;">CARACTERÍSTICAS DEL EQUIPO</font><br>
                                <strong>Marca: </strong>
                                <strong>Modelo: </strong><br>
                                <strong>Número de Serie: </strong>
                                <strong>Inventario: </strong><br>
                            </th>
                            <th>
                                <font style=" text-decoration: underline;">DESCRIPCIÓN DE LA FALLA O PROBLEMA</font><br>
                                <strong>Descripción detallada del problema: </strong> <br>
                        </tr>
                        <tr>
                            <th>
                                <font style=" text-decoration: underline;">STATUS GENERAL</font><br>
                                <strong>Estado del Reporte: </strong><br>
                                <strong>¿El problema tuvo solución?: </strong><font style="text-transform: uppercase;"></font><br>
                                <strong>Fecha de Finalización: </strong><br>
                                <strong>Hora de Finalización: </strong><br>
                            </th>
                            <th>
                                <font style=" text-decoration: underline;">ACTIVIDADES</font><br>
                                <strong>Actividad realizada: </strong><br><br>
                                <strong>Nombre del Prestador de Servicio: </strong><br>
                            </th>
                        </tr>                       
                        <tr>
                            <th>
                                <font style=" text-decoration: underline;">EVALUACIÓN DEL SERVICIO</font><br>
                                <strong>La Calidad del Servicio Otorgado por el Departamento de Soporte Técnico fue: </strong>
                                <br>
                                <strong>El Nivel de Atención Otorgado por el Departamento de Soporte Técnico fue: </strong>
                                <br>
                                <strong>El Nivel Profesional para que el Departamento de Soporte Técnico solucionará el problema fue: </strong>
                                <br>
                                <strong>El Tiempo de Respuesta en que el Departamento de Soporte Técnico lo atendió fue: </strong>
                                <br>
                                <strong>Evaluación General del Reporte: </strong>

                            </th>
                        </tr>

                    </table>
                    <div class="firma">________________________________________<br>FIRMA DE CONFORMIDAD DEL USUARIO
                    </div>                  
                </div>

This is about the styles, there is very little style that the page contains:

.imprimir{
    background: white;
    margin-right: 200px;
    margin-left: 200px;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    max-width: 1000px;
}
.imprimir table{
    max-width: 960px;
}
    
asked by Harrison Olvera 17.05.2018 в 22:32
source

2 answers

1

It has to do with the styles of the html at the moment of printing, what you should do is add the attribute media="all" to the styles like this when someone wants to print, for example:

<link rel="stylesheet" href="mis_estilos.css" type="text/css" media="all" />

If you want to have specific styles, different from what is shown on the page, you can create another .css file and then add it with the media="print" attribute.

<link rel="stylesheet" href="mis_estilos_imprimir.css" type="text/css" media="print" />

Another way is through the media query of .css , for example:

mis_estilos.css

@media print {
  .elemento {
    max-width: 100%;
  }
  .otro_elemento {
    max-width: 100%;
  }
}
    
answered by 17.05.2018 в 22:39
0

Mira I did some tests and to make it work the style must be inside the div you want to print

 function printDiv() {
          var objeto=document.getElementById('imprimir'); 
   
   //obtenemos el objeto a imprimir
          var ventana=window.open('','_blank');  //abrimos una ventana vacía nueva
          ventana.document.write(objeto.innerHTML);  //imprimimos el HTML del objeto en la nueva ventana
          ventana.document.close();  //cerramos el documento
          ventana.print();  //imprimimos la ventana
          ventana.close();  //cerramos la ventana
        }
.imprimir{
    background: white;
    margin-right: 200px;
    margin-left: 200px;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 20px;
    max-width: 1000px;
}
.imprimir table{
    max-width: 960px;
}
<div class="imprimir" id="imprimir">
  <!-- Compiled and minified CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" media="print">

  <div class="titulo">HOJA DE SERVICIOS INFORMATICOS</div>
  <table>
    <tr>
      <th>
        <font style=" text-decoration: underline;">DATOS DEL USUARIO</font><br>
        <strong>Usuario: </strong><br>
        <strong>Nombre del Responsable: </strong><br>
        <strong>Proveedor del Servicio: </strong><br>
        <strong>Área Solicitante: </strong><br>
      </th>
      <th>
        <font style=" text-decoration: underline;">DATOS DEL REPORTE</font><br>
        <strong>Número de Orden: </strong><br>
        <strong>Fecha de Registro: </strong><br>
        <strong>Hora de Registro: </strong><br>
        <strong>Reportó: </strong><br>
      </th>
    </tr>
    <tr>
      <th>

        <font style=" text-decoration: underline;">CARACTERÍSTICAS DEL EQUIPO</font><br>
        <strong>Marca: </strong>
        <strong>Modelo: </strong><br>
        <strong>Número de Serie: </strong>
        <strong>Inventario: </strong><br>
      </th>
      <th>
        <font style=" text-decoration: underline;">DESCRIPCIÓN DE LA FALLA O PROBLEMA</font><br>
        <strong>Descripción detallada del problema: </strong> <br>
    </tr>
    <tr>
      <th>
        <font style=" text-decoration: underline;">STATUS GENERAL</font><br>
        <strong>Estado del Reporte: </strong><br>
        <strong>¿El problema tuvo solución?: </strong>
        <font style="text-transform: uppercase;"></font><br>
        <strong>Fecha de Finalización: </strong><br>
        <strong>Hora de Finalización: </strong><br>
      </th>
      <th>
        <font style=" text-decoration: underline;">ACTIVIDADES</font><br>
        <strong>Actividad realizada: </strong><br><br>
        <strong>Nombre del Prestador de Servicio: </strong><br>
      </th>
    </tr>
    <tr>
      <th>
        <font style=" text-decoration: underline;">EVALUACIÓN DEL SERVICIO</font><br>
        <strong>La Calidad del Servicio Otorgado por el Departamento de Soporte Técnico fue: </strong>
        <br>
        <strong>El Nivel de Atención Otorgado por el Departamento de Soporte Técnico fue: </strong>
        <br>
        <strong>El Nivel Profesional para que el Departamento de Soporte Técnico solucionará el problema fue: </strong>
        <br>
        <strong>El Tiempo de Respuesta en que el Departamento de Soporte Técnico lo atendió fue: </strong>
        <br>
        <strong>Evaluación General del Reporte: </strong>

      </th>
    </tr>

  </table>
  <div class="firma">________________________________________<br>FIRMA DE CONFORMIDAD DEL USUARIO
  </div>
</div>

<button onclick="printDiv()">Imrpimir</button>

What I did was that I put a style inside, the one inside the div has media="print"

  

PS: Try it on your files for it to work since here it does not take me   Well, the snippet, but try it somewhere else and it works for me.

    
answered by 17.05.2018 в 23:16