'How to hide background contents of window.open while printing in Angular
I have running Angular 12 application and I am integrating the behavior to print report. I am able to achieve the print on button click which opens a new window, but I am not able to figure out how to achieve below things:
- Remove background contents on window.open so that the print window looks like a normal print window which we see by pressing Win+P in our browser.
- Center the print window popup in the screen.
- Not able to display images in print window. If I add any img tag in html like:
<img src="assets/images/galaxy.png" alt="">
, the image is not getting displayed in the print window. If I comment window.print() and just use window.open(), image is getting displayed
print.service.ts
showDialog() {
const factory =
this.componentFactoryResolver.resolveComponentFactory(PrintReportComponent);
const dialogComponentRef = factory.create(this.injector);
dialogComponentRef.instance.title = 'Report';
dialogComponentRef.changeDetectorRef.detectChanges();
//fetch the root DOM element of ModalComponent
const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
const WindowPrt = window.open(
'',
'',
'top=0,left=0,height=100%,width=auto'
);
WindowPrt.document.head.innerHTML = document.head.innerHTML;
WindowPrt.document.body.innerHTML = domElement.outerHTML;
WindowPrt.document.close();
WindowPrt.focus();
WindowPrt.print();
WindowPrt.close();
}
stackblitz link: https://stackblitz.com/edit/angular-ivy-c1ewya?file=src%2Fapp%2Fprint.service.ts
Solution 1:[1]
In this part :
const WindowPrt = window.open(
'',
'',
'top=0,left=0,height=100%,width=auto'
);
You have to remove '', ''.
change to :
const WindowPrt = window.open(
'top=0,left=0,height=100%,width=auto'
);
Solution 2:[2]
You should change your strategy at all. If you will do this, it will work. Please try this example one:
I added one dummy image in it and it is displayed.
Good luck ;)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | debugger |
Solution 2 | bazobehram |