1 import {Component, OnInit, TemplateRef, ElementRef, Renderer2} from '@angular/core';
2 import {PrintService, PrintRequest} from './print.service';
3 import {StoreService} from '@eg/core/store.service';
7 templateUrl: './print.component.html'
10 export class PrintComponent implements OnInit {
12 // Template that requires local processing
13 template: TemplateRef<any>;
15 // Context data used for processing the template.
18 // Insertion point for externally-compiled templates
19 htmlContainer: Element;
23 printQueue: PrintRequest[];
26 private renderer: Renderer2,
27 private elm: ElementRef,
28 private store: StoreService,
29 private printer: PrintService) {
30 this.isPrinting = false;
35 this.printer.onPrintRequest$.subscribe(
36 printReq => this.handlePrintRequest(printReq));
39 this.renderer.selectRootElement('#eg-print-html-container');
42 handlePrintRequest(printReq: PrintRequest) {
44 if (this.isPrinting) {
45 // Avoid print collisions by queuing requests as needed.
46 this.printQueue.push(printReq);
50 this.isPrinting = true;
52 this.applyTemplate(printReq);
54 // Give templates a chance to render before printing
56 this.dispatchPrint(printReq);
61 applyTemplate(printReq: PrintRequest) {
63 if (printReq.template) {
64 // Inline template. Let Angular do the interpolationwork.
65 this.template = printReq.template;
66 this.context = {$implicit: printReq.contextData};
70 if (printReq.text && true /* !this.hatch.isActive */) {
71 // Insert HTML into the browser DOM for in-browser printing only.
73 if (printReq.contentType === 'text/plain') {
74 // Wrap text/plain content in pre's to prevent
75 // unintended html formatting.
76 printReq.text = `<pre>${printReq.text}</pre>`;
79 this.htmlContainer.innerHTML = printReq.text;
83 // Clear the print data
85 this.isPrinting = false;
88 this.htmlContainer.innerHTML = '';
90 if (this.printQueue.length) {
91 this.handlePrintRequest(this.printQueue.pop());
95 dispatchPrint(printReq: PrintRequest) {
98 // Sometimes the results come from an externally-parsed HTML
99 // template, other times they come from an in-page template.
100 printReq.text = this.elm.nativeElement.innerHTML;
103 // Retain a copy of each printed document in localStorage
104 // so it may be reprinted.
105 this.store.setLocalItem('eg.print.last_printed', {
106 content: printReq.text,
107 context: printReq.printContext,
108 content_type: printReq.contentType,
109 show_dialog: printReq.showDialog
112 if (0 /* this.hatch.isActive */) {
113 this.printViaHatch(printReq);
115 // Here the needed HTML is already in the page.
120 printViaHatch(printReq: PrintRequest) {
122 // Send a full HTML document to Hatch
123 const html = `<html><body>${printReq.text}</body></html>`;
127 printContext: printReq.printContext,