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

Ways to append a number to the start or end of an array using JavaScript

Can you help me figure out why the function to order the "s" array from minor to major is adding the number at the end instead of the beginning? The if statement seems to be true (2 < 7 = true) but the logic is not working as expected. Any advice on how ...

Remove background image when input form field is in focus

I am currently experimenting with the following approach: $('input').on('click focusin', function() { $('.required').hide(); }); However, it appears that this logic is not functioning as intended. Here is an ...

Enhancing image clips using jQuery techniques

Could someone help me figure out why the image clip value isn't changing when I move the range slider in the code below? $('#myRange').on('input', function() { var nn = $(this).val(); $("img").css({ 'clip': ...

What is the best way to create a navigation bar that opens on the same page when clicked?

Can someone help me figure out how to create a navbar that, when clicked, opens a small window on the same page like in this example image? ...

Importing ES module into Next.js leads to ERR_REQUIRE_ESM

Encountered this issue while attempting to integrate ky into a Next.js project: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js It seems that the cause of this problem is Webpack (or Babel) converting all import ...

Choosing a random element in React: A step-by-step guide

I'm currently working on a dynamic website that aims to load a random header component upon each refresh. Despite my various attempts, the functionality operates smoothly during the initial load but consistently throws this error on subsequent refresh ...

The module 'atptest' could not be located or its corresponding type declarations are missing. Error code: ts(2307)

After creating an angular library using angular cli, I encountered an issue when trying to use it in any angular application after publishing it to npm. The published library installs successfully with the command: npm i atptest This is how I attempted t ...

What could be causing the state to continuously appear as null in my redux application?

Currently, I am in the process of developing a basic contacts application to gain expertise in React and Redux. The main focus right now is on implementing the feature to add a new contact. However, I have encountered an issue where the state being passed ...

After inputting the required parameters for the React onChange event, an unexpected error persists despite my efforts

I'm struggling with a bug in my React / typescript code. I have created a custom Input component that includes an 'onChange' property as described below: onChange?: (value?: string, event?: React.ChangeEvent<any>) => void; Here is ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...

Remove an item from an array and keep it stored efficiently without generating unnecessary waste

I'm interested in finding a high-performance method for removing and storing elements from an array. My goal is to create an object pool that minimizes the need for garbage collection calls. Similar to how .pop() and .unshift() remove elements from a ...

What is the best method to deactivate zoom in/out buttons using JavaScript?

As a newcomer to Phonegap, I've managed to implement zoom in/out functionality using websettings in the .java file. However, I now face a challenge where I need to disable/enable the zoom in/out buttons and stop scrolling at a specific point. I attemp ...

Ensure all asynchronous Ajax requests have completed before considering the page fully loaded

Many websites, such as YouTube, load the majority of their content after the DOM is ready using JavaScript. How can I ensure that all of these requests have been completed before injecting my code? window.onload = function() {}; The above code snippet do ...

Tips for identifying when a div reaches the top or bottom of the browser window in Angular 4

This question has solutions available for JQuery (which I prefer not to use in the current project) and Angular1 (which I am unfamiliar with). ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Guide on decrypting a file encrypted with C# using Node JS

I currently have encrypted files in C# using DES and PKCS7 encryption. My objective is to decrypt these files in Node JS. The decryption code in C# that I am using appears like this: public string SSFile_Reader( string fileToDecrypt ) { DESCryptoService ...

Load full html content, including doctype, into a jQuery container | Block scripts from running in iFrames

I am attempting to fetch an entire HTML file using AJAX and then manipulate the DOM with jQuery. This means that the retrieved HTML document includes a doctype and other top-level elements. The process of retrieving the HTML is straightforward: $.get(&ap ...

Using Ionic 5 to utilize local files for translation while offline

In my Ionic 5 app, I am utilizing translation with the following imports: import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; and loading it like thi ...

Issue with RequireJS: The data-main attribute fails to load the specified file

As I convert my small project into nodejs, I am facing an issue with the requireJS file that defines the JS to be used in the project not loading properly. Below is the structure of my project: https://i.sstatic.net/oYnqn.png The ng-app specifies the fr ...