diff --git a/src/lib/ngx-print.base.ts b/src/lib/ngx-print.base.ts index 2a0993c..ec9706d 100644 --- a/src/lib/ngx-print.base.ts +++ b/src/lib/ngx-print.base.ts @@ -188,7 +188,7 @@ export class PrintBase { */ protected print(printOptions: PrintOptions): void { - let styles = '', links = ''; + let styles = '', links = '', popOut = 'top=0,left=0,height=auto,width=auto'; const baseTag = this.getElementTag('base'); if (printOptions.useExistingCss) { @@ -196,6 +196,12 @@ export class PrintBase { links = this.getElementTag('link'); } + // If the openNewTab option is set to true, then set the popOut option to an empty string. + // This will cause the print dialog to open in a new tab. + if (printOptions.openNewTab) { + popOut = ''; + } + const printContents = this.getHtmlContents(printOptions.printSectionId); if (!printContents) { // Handle the case where the specified print section is not found. @@ -203,7 +209,14 @@ export class PrintBase { return; } - const popupWin = window.open("", "_blank", "top=0,left=0,height=auto,width=auto"); + const popupWin = window.open("", "_blank", popOut); + + if (!popupWin) { + // the popup window could not be opened. + console.error('Could not open print window.'); + return; + } + popupWin.document.open(); popupWin.document.write(` diff --git a/src/lib/ngx-print.directive.ts b/src/lib/ngx-print.directive.ts index a958652..0f0a3cb 100644 --- a/src/lib/ngx-print.directive.ts +++ b/src/lib/ngx-print.directive.ts @@ -68,6 +68,14 @@ export class NgxPrintDirective extends PrintBase { this.printOptions = { ...this.printOptions, bodyClass: value }; } + /** + * Whether to open a new window or default to new window. + * + */ + @Input() set openNewTab(value: boolean) { + this.printOptions = { ...this.printOptions, openNewTab: value }; + } + /** * * diff --git a/src/lib/ngx-print.service.spec.ts b/src/lib/ngx-print.service.spec.ts index c95f79f..3b2a667 100644 --- a/src/lib/ngx-print.service.spec.ts +++ b/src/lib/ngx-print.service.spec.ts @@ -148,6 +148,19 @@ describe('NgxPrintService', () => { expect(service.print).toHaveBeenCalledWith(customPrintOptions); }); + it('should open new tab', () => { + spyOn(service, 'print'); + + const customPrintOptions: PrintOptions = new PrintOptions({ + printSectionId: 'print-section', + openNewTab: true + }); + + component.printMe(customPrintOptions); + + expect(service.print).toHaveBeenCalledWith(customPrintOptions); + }); + it('should test the printStyle', () => { // Create a spy on the instance's method diff --git a/src/lib/print-options.ts b/src/lib/print-options.ts index bf67bc9..14d2c54 100644 --- a/src/lib/print-options.ts +++ b/src/lib/print-options.ts @@ -3,6 +3,7 @@ export class PrintOptions { printTitle: string = null; useExistingCss: boolean = false; bodyClass: string = ''; + openNewTab: boolean = false; previewOnly: boolean = false; closeWindow: boolean = true; printDelay: number = 0;