Tuesday, May 15, 2018

SSRS Reports in an Angular App (Part 3 - Printing the Report)

I recently wrote the first and second parts of this series on displaying SSRS reports in an Angular application. At the end of the second post I had a report, in PDF format, being displayed via a 3rd party component in my Angular application and I was ready to allow the user to print the report. Let's pick up from there.

Printing a PDF seems pretty straight forward at first: I should just be able to run the window.print JavaScript function and be all set. Of course, it isn't actually that simple because then I wouldn't be writing this post.

Our project has a requirement to support Chrome, Firefox, Safari, and Edge so I needed a solution that would work in all browsers. After a bit of digging I found that I'd need to do a little bit of dancing around Edge (big shocker there), but the other three would readily support the method I wanted to use. The route that made the most sense was to use the built-in (mostly) createObjectUrl function to build a URL from a Blob created from the PDF bytes, then open that URL in a new window. That was easy enough:
   1:  print(): void {
   2:    const url = URL.createObjectUrl(new Blob([this.reportBytes], { type: 'application/pdf' }));
   3:    window.open(url);
   4:  }

As I wrote before, this worked fine for most of the browsers, but Edge wasn't happy so I had to modify it to work:
   1:  print(): void {
   2:    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
   3:      window.navigator.msSaveOrOpenBlobBlob([this.reportBytes]));
   4:    } else {
   5:      const url = URL.createObjectUrl(new Blob([this.reportBytes], { type: 'application/pdf' }));
   6:      window.open(url);
   7:    }
   4:  }

This isn't a perfect solution because the report doesn't actually print right away when you click the Print button. It doesn't even invoke the native print function of the browser. It does, however, open the PDF in a new tab and allow the user to print it if they wish. We had to go that route because Edge had some issues launching the print dialog properly with a PDF (which goes back to not being able to use the createObjectUrl function). Not perfect, but good enough.
  1. Display a list of all reports in SSRS
  2. Allow the user to click on a single report to view the report
  3. Allow the user to print the report
  4. Allow the user to download the report
Update: All four parts of this series are complete now.
  1. SSRS Reports in an Angular App (Part 1 - Showing the Report)
  2. SSRS Reports in an Angular App (Part 2 - Showing the Report (correctly))
  3. SSRS Reports in an Angular App (Part 3 - Printing the Report)(this post)
  4. SSRS Reports in an Angular App (Part 4 - Downloading the Report)

No comments:

Post a Comment