How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the child window for this process. Any suggestions or advice would be greatly appreciated!

Answer №1

Check out the code snippet below:

This code will launch a new tab with this page and trigger the print dialog.

Give the page some time to load by adjusting the setTimeout function as per your requirement.

var openPrintDialog = window.open(document.URL, '_blank');
setTimeout(openPrintDialog.print(), 3000);

Answer №2

Encountered a similar situation when attempting to enable users to view and print a QR image in a new tab. This is how I accomplished it:

  prepareQRForPrint(source: string) {
    return "<html><head><style type='text/css' media='print'>@media print { @page { size: auto; margin: 0;} body { margin:1.6cm; } }</style><script>function step1(){\n" +
      "setTimeout('step2()', 2);}\n" +
      "function step2(){window.print();window.close()}\n" +
      "</scri" + "pt></head><body onload='step1()'>\n" +
      "<img style='width:800px;height:1000px;' src='" + source + "' /></body></html>"
  }

  printPreviewQR(source: string) {
    let Pagelink = "about:blank";
    var pwa = window.open(Pagelink, "_new");
    pwa.document.open();

    pwa.document.write(this.prepareQRForPrint(source));
    pwa.document.close();
  }

In order to use this function, you can do the following:

<a href="javascript: void(0)" (click)="printPreviewQR(QRPath)">QR-Code</a>

Answer №3

This code snippet is suitable for implementation in Angular version 12

/* 
To print the content within a specific element, use ViewChild to reference that element.
*/
@ViewChild('PackageSlipPrint', { static: true }) printableRef?: ElementRef;

print() {
    var printContent = this.docRef.nativeElement.outerHTML;
     
    var newTab = window.open('') as Window;
    newTab.document.open();
    newTab.document.write(printContent);
    setTimeout(() => {
        newTab.stop();
        newTab.print();
        newTab.close();
    }, 300);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encounter an issue during npm installation of electron: "Error verifying the initial certificate."

I recently developed a new app directory and ran the command npm init. However, I encountered an issue while trying to install Electron with the following line of code: npm install electron --save-dev. The error message I received is as follows: > [em ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...

Creating Algorithms for Generic Interfaces in TypeScript to Make them Compatible with Derived Generic Classes

Consider the (simplified) code: interface GenericInterface<T> { value: T } function genericIdentity<T>(instance : GenericInterface<T>) : GenericInterface<T> { return instance; } class GenericImplementingClass<T> implemen ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Troubleshooting CORS Problem with AWS CloudFront Signed Cookies

I encountered an issue while implementing cloudfront signed cookies. When trying to access '' from '', the CORS policy blocked it due to absence of the 'Access-Control-Allow-Origin' header. This problem arose after rest ...

Ways to verify if an item is an Express object?

Currently, I am utilizing typescript to verify whether an app returned by the Express() function is indeed an instance of Express. This is how I am attempting to accomplish this: import Express from "express" const app = Express() console.log( ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

How do I specify the default checked value for a checkbox in Redux Form?

Within our Redux Form 5.3 application (not version 6.x), the goal is to display an <input type="checkbox" /> in this manner: // Sometimes, fieldHelper.checked starts off as undefined. When a checkbox is // clicked by the user, fieldHelper.checked is ...

What is the maximum amount of information that can be stored in a data attribute within the DOM?

Occasionally, I find myself wanting to include a substantial amount of data on the webpage in order to minimize additional AJAX calls for dynamic content. However, I am concerned about potential performance implications. Is there a penalty I should be aw ...

Revamping the static method signature of a class in Typescript

One of the modules I'm using is called some-module and it defines a class like this: export declare class Some<T> { ... static create<T>(): Some<T>; map<U>(x: U): Some<U>; } export default Some In my project, I ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

Encountering the error message "Subscribe is not a function in Jasmine" while

Encountering an issue where I am receiving an error stating "subscribe is not a function" in Angular unit testing. Here is the call that I have implemented in my component: this.myService.employees.subscribe(emp => this.emp = emp); Despite creating a ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

What is causing my Javascript media query for the sidebar to not function properly?

I am working on implementing a sidebar that slides out 250px using JavaScript on the desktop view. However, I want the sidebar to take up 100% width when viewed on mobile devices. Despite my attempts to use Media Queries in JavaScript to achieve this, I am ...

Stop repeated form submissions in Angular using exhaust map

How can we best utilize exhaust Matp to prevent multiple submissions, particularly when a user is spamming the SAVE button? In the example provided in the code snippet below, how do we ensure that only one submission occurs at a time even if the user click ...

Creating a stylish CSS button with split colors that run horizontally

Could you please provide some guidance on creating a button design similar to this one? I've made progress with the code shown below, but still need to make adjustments like changing the font. <!DOCTYPE html> <html> <head> <sty ...

Learn how Angular 2 allows you to easily add multiple classes using the [class.className] binding

One way to add a single class is by using this syntax: [class.loading-state]="loading" But what if you want to add multiple classes? For example, if loading is true, you want to add the classes "loading-state" and "my-class". Is there a way to achieve t ...

Is there a way to retrieve all properties within a Typescript Class that includes optional properties?

If we have a scenario where: class ExampleType { item1?: string, item2?: string } and all the properties are OPTIONAL. Is there a way to generate an array of property names like: ["item1", "item2"] I attempted to use console.log( ...

Tips on how to modify the session type in session callback within Next-auth while utilizing Typescript

With my typescript setup, my file named [...next-auth].tsx is structured as follows: import NextAuth, { Awaitable, Session, User } from "next-auth"; // import GithubProvider from "next-auth/providers/github"; import GoogleProvider from ...