I am working on an Angular 4 app and have a function to print content. Below is a snippet from my TypeScript file:
print(id) {
// console.log(temp)
this.templateservice.getTemplateById(id).subscribe(template => {
if (!template.success) {
this.snackbar.open(template.message, '', {
duration: 2000,
extraClasses: ['success-snackbar']
});
} else {
let headContents, innerContents, signContents, popupWin;
headContents = document.getElementById('head-section').innerHTML;
innerContents = document.getElementById('inner-section').innerHTML;
signContents = document.getElementById('sign-section').innerHTML;
console.log(headContents);
popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
console.log(popupWin)
popupWin.document.open();
popupWin.document.write('<html><head><style></style></head><body onload="window.print();window.close()"><p class="head">' + headContents + '</p> <p class="inner">' + innerContents + '</p> <p class="sign">' + signContents + '</p></body></html>');
popupWin.document.close();
}
});// end of subscribe
}//end of print
And this is part of my HTML file:
<md-tab>
<ng-template md-tab-label>Outgoing Mail</ng-template>
<md-card-content >
<div fxLayout="column" fxLayoutAlign="center center" class="mt-1" >
<div class="template" style="@page {size: A4};width: 210mm;height: 297mm;border-width: 2px;border-style: solid;border-color: #e6e6e6;padding-top: 23mm;padding-left: 2cm;padding-right: 2.5cm;padding-bottom: 55mm">
<p class="head" id="head-section" style="line-height: 1cm;padding-left: 152mm;">Mail Number: {{mail_number}} <br> Date: {{created_at| date:'yyyy MMM dd'}}</p>
<p class="inner" id="inner-section" style="max-height: 873px;line-height: 25px;word-spacing:1px;text-align: justify;padding-right: 20mm;padding-left: 25mm;padding-top: 21mm;padding-bottom: 5mm;white-space: pre-wrap; width: 166mm; word-wrap: break-word;">{{content}}</p>
<p class="sign" id="sign-section" style="padding-left: 33mm;padding-right: 147mm ;padding-bottom: 70mm;line-height: 1cm;">Sincerely <br> {{sender}}</p>
</div>
</div>
</md-card-content>
</md-tab>
Currently, I am encountering an error "cannot read property document of undefined." Moving the print codes outside of the subscribe block does not allow me to access the template returned by the service. When I use console.log(headContents)
, I get a response. However, when I use console.log(popupwin)
, I get the image below! The popupWin is null and I receive an error relating to the document.