1

I have been trying for a couple of weeks now to print a label using angular. I am able to get the label to print with no issues. The issue is it loses the formatting of the label in the preview print and also printing. I have tried a lot of the code floating around and no matter which function I run the HTML through I get the same results. I have also tried a combo of the .ts, .html, and scss.component. The code is below on what is working now to the point it needs to print. Also to note this is a modal pop up.

   printDiv(): void {
    var divContents = document.getElementById("GFG").innerHTML;
    var a = window.open('', '', 'height=500, width=500');
    a.document.write('<html>');
    a.document.write('<body > <h1>Div contents are <br>');
    a.document.write(divContents);
    a.document.write('</body></html>');
    a.document.close();
    a.print();
}
@media print {
    body * {
      visibility: hidden;
    }
    #section-to-print, #section-to-print * {
      visibility: visible;
    }
    #section-to-print {
      position: absolute;
      left: 0;
      top: 0;
    }
  }
<div  id="GFG" class="divTable">
    <div class="divTableBody">
    <div class="divTableRow">
    <div class="divTableCell">
        <br />
        <scl-ngx-qrcode [text]="qrCodeString" [options]="options"></scl-ngx-qrcode>
        <br />
    </div>
    <div class="divTableCell">
        <h4 class="text-center">COC: 23456</h4>
        <div>{{ CompanyName }}</div>
        <div>{{ AddressLine1 }}</div>
        <div>{{ AddressLine2 }}</div>
        <div>{{ City }}, {{ PostalCode }}</div>
        <div>{{ PhoneNumber }}
        <div>{{ PrjCode }}</div>
    </div>
    <div class="divTableRow">
    <div class="divTableCell">
        <h1 class="display-2 text-center">RUSH</h1>
        <br/>
        Container _____ of _____
        <br/>
    </div>
    <div class="divTableCell">&nbsp;</div>
    </div>
    </div>
    </div>
    <button (click)="printDiv()">Print Label(s)</button>

1 Answers1

0

Css classes aren't in the new window document's scope. To it (even with innerHTML) class divTable is just nowhere to be found. Seems like your not attaching any stylesheets either for the new document. https://stackoverflow.com/a/43110489/15439733

a.document.write('<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">';

Other option would be to attach styling as you create the document which could be even more simpler than attaching a style sheet. https://stackoverflow.com/a/53864968/15439733


Here is a working example how to attach a stylesheet on write to document.

https://jsfiddle.net/Nurech/gn76wd1x/2/

For more information about this: https://timdeschryver.dev/blog/print-css-with-angular#adding-a-print-button

Joosep Parts
  • 5,372
  • 2
  • 8
  • 33