Nathan Foss
Nathan Foss

Reputation: 680

Javascript - Print Blob Content Returned from API

I'm building a page for my angular2 web application where a user can select customers from a list and print off letters to mail them. These letters were uploaded as PDFs and are stored as varbinary in the database.

In the case of multiple selections, I'm simply appending byte[]'s so the user will print one document containing all of the letters to send to customers.

I'm able to pull the blob successfully from the API and return it with the content type application-pdf but then I don't know what to do with it from there.

Here's my Angular2 Component API Call:

this.printQueueService.getPrintContent(printRequests) //customers to receive letters
            .subscribe((data: Blob) => {
                var element: HTMLIFrameElement = <HTMLIFrameElement>document.getElementById('printFile');
                element.innerText = data + ""; //what do I do with the blob?
                element.contentWindow.print();
});

HTML Element:

<iframe id="printFile" style="display:none"></iframe>

I know I can just download the PDF and prompt the user to print using a PDF Viewer, but I'd rather not force users to go through extra steps.

I'd also rather not try to render the PDF in the browser and print because it assumes users have the proper plugins and browsers support it.

What options do I have for printing a blob in the browser?

Upvotes: 7

Views: 15486

Answers (1)

Nathan Foss
Nathan Foss

Reputation: 680

As per suggestions from Daniel A. White, I solved this issue. I decided not to use an IFrame because these print files could be massive and the print() function includes the page name as footnotes.

Instead, I chose to open the generated PDF in a new tab as follows:

if (window.navigator.msSaveOrOpenBlob) {
     window.navigator.msSaveOrOpenBlob(data, "PrintedLetters.pdf"); //IE is the worst!!!
}
else {
     var fileURL = URL.createObjectURL(data);
     var a: HTMLAnchorElement = document.createElement('a');
     a.href = fileURL;
     a.target = '_blank';
     document.body.appendChild(a);
     a.click();
}

Upvotes: 5

Related Questions