javascriptangularprintjs

Printing multiple files in angular


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

Solution

  • 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);