angulargoogle-chromemedia-queriesprinting-web-page

Unable to change the margin & layout for printing in chrome browser from angular 2


I'm trying to print HTML but I'm not able to change the layout and margin of the chrome browser (refer the attached image).

This 1) Layout & 2) Margin remains the same

PRINT() {
  window.print();
}
@media print {
  .doNotPrint {
    display: none;
  }
  * {
    -webkit-print-color-adjust: exact;
  }
  @page {
    margin: 0 !important;
    size: A4 Landscape !important;
    -webkit-print-color-adjust: exact;
  }
  html,
  body {
    margin: 0 !important;
    size: A4 Landscape !important;
    -webkit-print-color-adjust: exact;
  }
}
<form [ngClass]="themeSRVC.currentThemeNAME" fxLayout="column" fxFlex>
  <!-- navBAR -->
  <mat-toolbar id="idPrimaryTOOLBAR" color="primary" class="doNotPrint">
    <mat-toolbar-row>
      <button mat-icon-button type="button" (click)="routeSRVC.goBACK()">
        <mat-icon matTooltip="Go Back">arrow_back</mat-icon>
      </button>
      <span class="fillSPACE"></span>
      <button mat-icon-button (click)="PRINT()">
        <mat-icon matTooltip="print">print</mat-icon>
      </button>
    </mat-toolbar-row>
  </mat-toolbar>

  <!-- *****printableCONTENT***** -->
  <div id="idToPRINT" fxFlex>

    <div fxLayout="row">
      <div fxFlex="33" style="height:200px;background-color:red">Left</div>
      <div fxFlex style="height:200px;background-color:yellow">Center</div>
      <div fxFlex="33" style="height:200px;background-color:green"> Right</div>
    </div>


  </div>

</form>

Am I missing something..? please help me to remove the margin and change the layout.


Solution

  • After hours and hours of research... I finally figured it out.!

    set @media styles in the global styles.scss of your app.

    NOT in the component.scss

    If you want to dynamically change the layout to portrait/landscape you can do like the following

    1) Remove the @media print{...} from the global scss

    2) and in your component.ts call the print function by passing true/false

    PRINT(landscape: boolean) {
      var head = document.head || document.getElementsByTagName('head')[0];
      var style = document.createElement('style');
      style.type = 'text/css';
      style.media = 'print';
    
      style.appendChild(document.createTextNode(landscape ?
        '@page { size: A4 landscape; margin: 0in;}' :
        '@page { size: A4;  margin: 0in; }'));
    
      head.appendChild(style);
      window.print();
    }