How to send file direct to user machine default printer from angular application
Loading
How to send file direct to user machine default printer from angular application
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jayraj ChhayaRank #304 · 8.2K reputationPosted Aug 29, 2024, 1:45 AM EDT
Sending a file directly to a user's default printer from an Angular application involves a few steps, primarily due to browser security restrictions. While you cannot directly access the printer from the client-side code, you can facilitate printing by using the browser's built-in print functionality.
Here’s a simple approach:
Create a Print Function: You can create a function that opens a new window or a print dialog with the content you want to print.
Use a Blob for File Handling: If you have a file (like a PDF), you can convert it to a Blob and create a URL for it.
Invoke the Print Dialog: Use the
window.print()method to open the print dialog.printFile(file: Blob) { const fileURL = URL.createObjectURL(file); const printWindow = window.open(fileURL); printWindow.onload = () => { printWindow.print(); printWindow.close(); }; }Meet ShahRank #1,739 · 868 reputationPosted Aug 29, 2024, 9:40 AM EDT
To send a file directly to a user's default printer from an Angular application, you must rely on the browser's printing capabilities since Angular runs in a browser environment (client side) and does not have direct access to system-level functionalities like printing.
But there are multiple ways to achieve this.
1. Print HTML content direct - for that in HTML code you need to wrap your text like this below code for it.
This is the content to print
More content goes here...
Associate Ts FIle code.
// print.component.ts import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-print', templateUrl: './print.component.html' }) export class PrintComponent { @ViewChild('printSection') printSection: ElementRef; print() { const printContent = this.printSection.nativeElement.innerHTML; const WindowPrt = window.open('', '', 'width=800,height=600'); WindowPrt.document.write('
2. Use a Printing Library
print-jsLibrary: - npm install print-js// print-file.component.ts
import { Component } from '@angular/core';
import printJS from 'print-js';
@Component({
selector: 'app-print-file',
template: ``
})
export class PrintFileComponent {
print() {
printJS({ printable: 'path/to/your/file.pdf', type: 'pdf' }); //Directly you can call library function and pass the your pdf path or source of it.
}
}