qz is not defined qz_tray

4k Views Asked by At

I have been looking for a solution to print from web on client side this (https://medium.com/@yehandjoe/angular-2-raw-printing-service-56614d358754) is what i have been following it suggests to use qz tray to get access for printer. I have copied the code as it is but its not working.

whenever the function getprinters() is executed it says "qz is not defined"

i have imported packages using these npm commands

npm install qz-tray sha ws

npm install rsvp, this is my printer service code :

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';


declare var qz: any;
@Injectable()
export class PrinterService {
constructor() { }

errorHandler(error: any): Observable<any> {
    return Observable.throw(error);
}

// Get list of printers connected
getPrinters(): Observable<string[]> {
    return Observable
        .fromPromise(qz.websocket.connect().then(() => qz.printers.find()))
        .map((printers: string[]) => printers)
        .catch(this.errorHandler);
}

// Get the SPECIFIC connected printer
getPrinter(printerName: string): Observable<string> {
    return Observable
        .fromPromise(qz.websocket.connect().then(() => qz.printers.find(printerName)))
        .map((printer: string) => printer)
        .catch(this.errorHandler);
}

// Print data to chosen printer
printData(printer: string, data: any): Observable<any> {
    // Create a default config for the found printer
    const config = qz.configs.create(printer);
    return Observable.fromPromise(qz.print(config, data))
        .map((anything: any) => anything)
        .catch(this.errorHandler);
}

// Disconnect QZ Tray from the browser
removePrinter(): void {
    qz.websocket.disconnect();
}

}

Kindly Correct if i am doing any mistake or i would really appreciate any other alternate solution

3

There are 3 best solutions below

2
On BEST ANSWER

It looks like you need to import qz tray to your provider.

I used SHA.js: https://www.npmjs.com/package/sha.js for encryption and used native promises.

So I added the following lines to the top of the file below the existing imports:

import * as shajs from 'sha.js';
import * as qz from 'qz-tray';

Set SHA for QZ

Remember to tell QZ to use the new sha.js package with this:

qz.api.setSha256Type(function (data) {
    return shajs('sha256').update(data).digest('hex')
});

Set Native Promises for QZ

Remember to tell QZ to use the new sha.js package with this:

qz.api.setPromiseType(function (resolver) {
    return new Promise(resolver);
});
0
On

Try to declare this in constructor or before it, you variable before of declaration of service class, it doesn't see variable

0
On

i also needed to use this QZ service, it looks like the only way to communicate with a printer from a javascript app.

anyway, thanks to the answer above, and some articles, i succeeded to make a small angular 7 app, witch connect verry easily with the printer.

i felt like sharing this code just in case someone had to go to the same process. and it looks like this is the only post about QZ Tray. first, you should install the necessary dependencies by executing:

npm install qz-tray js-sha256 rsvp --save

secondly, you should create a printing service, here is the its code:

import { Injectable } from '@angular/core';
import { from as fromPromise, Observable, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';

import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';

@Injectable({
  providedIn: 'root'
})
export class PrinterService {

  //npm install qz-tray js-sha256 rsvp --save
  constructor() {
    qz.api.setSha256Type(data => sha256(data));
    qz.api.setPromiseType(resolver => new Promise(resolver));
  }
  // Get the list of printers connected
  getPrinters(): Observable<string[]> {
    console.log('+++++++++PrinterService+++++');
    return fromPromise(
      qz.websocket.connect().then(() => qz.printers.find())
    )
    map((printers: string[]) => printers)
      , catchError(this.errorHandler);
  }

  // Get the SPECIFIC connected printer
  getPrinter(printerName: string): Observable<string> {
    return fromPromise(
      qz.websocket.connect()
        .then(() => qz.printers.find(printerName))
    )
    map((printer: string) => printer)
      , catchError(this.errorHandler);
  }

  // Print data to chosen printer
  printData(printer: string, data: any): Observable<any> {
    const config = qz.configs.create(printer);

    return fromPromise(qz.print(config, data))
    map((anything: any) => anything)
      , catchError(this.errorHandler);
  }

  private errorHandler(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.log(error.error);
      console.log('An error occurred:', error.status);
      return throwError(error.error);
    } else {
      console.log('An error occurred:', error.status);
      console.log(error.error);
      return throwError(error.error);
    }
  };
}

finally, you should just call your service from some component, and execute the functions, in this case, i used the app component:

import { Component } from '@angular/core';
import { PrinterService } from './printer.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'qz-tray-example';
  printers: string[];

  constructor(public _printerService: PrinterService) {

  }

  ngOnInit() {
    this.printers = [];
    console.log('AppComponent____________');
    this._printerService.getPrinters().subscribe(
      data => {
        console.log(data);
        // this.printers = data;
        this.print();
      },
      err => {
        console.log(err);
      }
    );
  }

  print() {



    let content1 = `
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        </head>

        <body>
            <div> 
                <h3>Printing Test 1</h3>
            </div>
        </body>
    </html>`;

    let content2 = `
    <html>
        <head>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        </head>

        <body>
            <div> 
                <h3>Printing Test 2</h3>
            </div>
        </body>
    </html>`;
    var data = [{
      type: 'html',
      format: 'plain', // or 'plain' if the data is raw HTML
      data: content1
    },
    {
      type: 'html',
      format: 'plain', // or 'plain' if the data is raw HTML
      data: content2
    }];
    data[0].data = content1;
    this._printerService.printData('zebra', data).subscribe(
      data => {
        console.log('ok print');
      },
      err => {
        console.log(err);
      }
    );
  }
}

hope that this answer help someone to get started with his app, good luck ;).