Imprimir plantilla Html en Angular 2 (ng-imprimir en Angular 2)


Quiero imprimir la plantilla HTML en angular 2. Había explorado acerca de esto Tengo solución en angularjs 1 Imprimir Plantilla Html en Angularjs 1

Cualquier sugerencia sería apreciada

Author: Neeraj Rathod, 2016-12-29

6 answers

Así es como lo he hecho en angular2 (es similar a la solución plunkered) En tu archivo HTML:

<div id="print-section">
  // your html stuff that you want to print
</div>
<button (click)="print()">print</button>

Y en su archivo TS :

print(): void {
    let printContents, popupWin;
    printContents = document.getElementById('print-section').innerHTML;
    popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    popupWin.document.open();
    popupWin.document.write(`
      <html>
        <head>
          <title>Print tab</title>
          <style>
          //........Customized style.......
          </style>
        </head>
    <body onload="window.print();window.close()">${printContents}</body>
      </html>`
    );
    popupWin.document.close();
}
 58
Author: selem mn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-29 12:39:00

En caso de que alguien más se encuentre con este problema, si ya ha establecido la página, le recomendaría usar media queries para configurar su página de impresión. A continuación, simplemente puede adjuntar una función de impresión a su botón html y en su ventana de llamada de componentes.print();

Componente.html:

<div class="doNotPrint">
    Header is here.
</div>

<div>
    all my beautiful print-related material is here.
</div>

<div class="doNotPrint">
    my footer is here.
    <button (click)="onPrint()">Print</button>
</div>

Componente.ts:

onPrint(){
    window.print();
}

Componente.css:

@media print{
  .doNotPrint{display:none !important;}
}

Opcionalmente también puede agregar otros elementos / secciones que no desea imprimir en la consulta de medios.

Usted puede cambie los márgenes del documento y todo en la consulta de impresión también, lo que lo hace bastante poderoso. Hay muchos artículos en línea. Aquí hay uno que parece completo: https://www.sitepoint.com/create-a-customized-print-stylesheet-in-minutes / También significa que no tiene que crear un script separado para crear una 'versión impresa' de la página o usar mucho javascript.

 11
Author: Farasi78,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-10 16:45:55

Puedes hacer así en angular 2

En el archivo ts

 export class Component{          
      constructor(){
      }
       printToCart(printSectionId: string){
        let popupWinindow
        let innerContents = document.getElementById(printSectionId).innerHTML;
        popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWinindow.document.open();
        popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>');
        popupWinindow.document.close();
  }

 }

En html

<div id="printSectionId" >
  <div>
    <h1>AngularJS Print html templates</h1>
    <form novalidate>
      First Name:
      <input type="text"  class="tb8">
      <br>
      <br> Last Name:
      <input type="text"  class="tb8">
      <br>
      <br>
      <button  class="button">Submit</button>
      <button (click)="printToCart('printSectionId')" class="button">Print</button>
    </form>
  </div>
  <div>
    <br/>
   </div>
</div>
 10
Author: Vikash Dahiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-29 13:59:01

Servicio de impresión

import { Injectable } from '@angular/core';

@Injectable()
export class PrintingService {

public print(printEl: HTMLElement) {
    let printContainer: HTMLElement = document.querySelector('#print-container');

    if (!printContainer) {
      printContainer = document.createElement('div');
      printContainer.id = 'print-container';
    } 

    printContainer.innerHTML = '';

    let elementCopy = printEl.cloneNode(true);
    printContainer.appendChild(elementCopy);
    document.body.appendChild(printContainer);

    window.print();
  }
}

Componente que quiero imprimir

@Component({
  selector: 'app-component',
  templateUrl: './component.component.html',
  styleUrls: ['./component.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class MyComponent {
  @ViewChild('printEl') printEl: ElementRef;

  constructor(private printingService: PrintingService) {}

  public print(): void {
    this.printingService.print(this.printEl.nativeElement);
 }

}

No es la mejor opción, pero funciona.

 1
Author: Kliment Ru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-13 06:27:40

La mejor opción que encontré para resolver esto sin tener problemas con mis estilos fue usar una ruta separada para mi salida impresa y cargar esta ruta en un iframe.

Mi componente circundante se muestra como una página de pestañas.

@Component({
  template: '<iframe id="printpage" name="printpage" *ngIf="printSrc" [src]="printSrc"></iframe>',
  styleUrls: [ 'previewTab.scss' ]
})
export class PreviewTabPage {
  printSrc: SafeUrl;

  constructor(
    private navParams: NavParams,
    private sanitizer: DomSanitizer,
  ) {
    // item to print is passed as url parameter
    const itemId = navParams.get('itemId');

    // set print page source for iframe in template
    this.printSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.getAbsoluteUrl(itemId));
  }

  getAbsoluteUrl(itemId: string): string {
    // some code to generate an absolute url for your item
    return itemUrl;
  }
}

El iframe solo carga la ruta de impresión que representa un componente de impresión en la aplicación. En esta página, la impresión puede activarse después de que la vista se inicialice por completo. Otra forma podría ser un botón de impresión en el componente padre que desencadena la impresión en el iframe por window.frames["printpage"].print();.

@Component({
  templateUrl: './print.html',
  styleUrls: [ 'print.scss' ]
})
export class PrintPage implements AfterViewInit {

  constructor() {}

  ngAfterViewInit() {
    // wait some time, so all images or other async data are loaded / rendered.
    // print could be triggered after button press in the parent component as well.
    setTimeout(() => {
      // print current iframe
      window.print();
    }, 2000);
  }

}
 0
Author: Dave Gööck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-24 18:50:06

Como una extensión de la respuesta aceptada,

Para obtener los estilos existentes que necesita para preservar el aspecto y la sensación del componente de destino, puede realizar una consulta para extraer los elementos <style> del documento de nivel superior e inyectarlo en la cadena HTML.

const getStylesHtml = (document: Document): string =>
{
    const styles: string[] = [];

    const styleElements = document.getElementsByTagName('style');
    for (let idx = 0; idx < styleElements.length; idx++)
    {
        styles.push(styleElements[idx].outerHTML);
                                       ^^^^^^^^^ whole element, not just contents
    }

    return styles.join('\r\n');
};

Luego en el fragmento existente:

const printContents = document.getElementById('print-section').innerHTML;
const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
        <title>Print tab</title>
        ${getStylesHtml(document)}
                       ^^^^^^^^^^ pass reference to the document
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Ahora usando estilos existentes (los componentes angulares crean un estilo acuñado por sí mismos), así como marcos de estilo existentes (por ejemplo, Bootstrap, MaterialDesign, Bulma) debería verse como un fragmento de la pantalla existente

 0
Author: lenard-bernardo-ei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-08 06:35:51