0

I have multiple blobs from which i am creating blob urls and using print-js library to show print preview screen of browser.

I have

async printDocuments(): Promise<any> {
    const _files: { fileName: string, blob: any }[] = await this._getFiles();
    _files.forEach((_fileInfo, index) => {
        const blobUrl = URL.createObjectURL(_fileInfo.blob);
        printJS(blobUrl);
    });
}

but this shows print preview dialog for just first file.

How can I print all the documents either by merging or opening multiple printing windows.

I tried using this

printJS({
    printable: _files[0].blob,
    type: "pdf",
    onPrintDialogClose: () => {
      console.log("nex");
    }
});

but now it is showing

core.js:4196 ERROR Error: Uncaught (in promise): TypeError: params.printable.charAt is not a function
TypeError: params.printable.charAt is not a function
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • 1
    Try using the library `onPrintDialogClose` and only trigger the next print job once the first one it's done. The browser may be ignoring the other jobs since they are being triggered before the first one is processed. https://printjs.crabbly.com/#configuration – crabbly Aug 05 '20 at 18:40
  • @crabbly, updated the question, can you help – Sunil Garg Aug 11 '20 at 05:33

1 Answers1

1

onPrintDialogClose worked for me.

Here is what I did

async printDocuments(): Promise<any> {
     const _files: { fileName: string, blob: any }[] = await this._getFiles();
     if (_files && _files.length > 0) {
            this._printDocument(_files, 0);
     }
}

private _printDocument(files: { fileName: string, blob: any }[], index: number): void {
    const blobUrl = URL.createObjectURL(files[index].blob);
    printJS({
        printable: blobUrl,
        type: "pdf",
        onPrintDialogClose: () => {
            index = index + 1;
            if (index < files.length) {
                this._printDocument(files, index);
            }
        }
    });
}

Here is the documentation

Thanks to @crabbly

Edit - Latest chrome does not work with callback

With the latest chrome, onPrintDialogClose is not working. For this remove the onPrintDialogClose from printJs call and add the following code after printJs call.

// fix : printjs issue #495
const handler = () => {
    // Make sure the event only happens once.
    window.removeEventListener("mouseover", handler);

    // function that you want to execute for onPrintDialogClose
    onCloseCallback();

    // Remove iframe from the DOM, by default 'printJS'
    const iframe = document.getElementById("printJS");

    if (iframe) {
        iframe.remove();
    }
    };
setTimeout(() => { window.addEventListener("mouseover", handler); }, 1000);
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189