For one of our clients we needed a “Save As” or “Print As” dialog option specifically for PDF files(invoices and such). Unfortunately there are no native components or wrappers which handle this specific case using Blazor. So we started building our own.

The final result

Exploring the alternatives

In our initial release we tried to use the built-inNavigationManager. Which can easily download a file (even if the file is returned by a Controller action or on any other domain) using the foreLoadparameter. I even recall an entire discussion about it on the old Blazor repository in the early days of Blazor (2018). But unfortunately it just downloads a file, the client still had to open every .PDF, click print, close the PDF which was quite cumbersome… What they really wanted is to click and print, so using the download option wasn’t really helping us out here…

At the time of writing this post, this option is currently not possible due to some regression bug, which caused quite some trouble in our production environment (to say the least). Which made the need for a descent printing solution even more demanding. If you had some issues downloading files, you might have seen the following issue passing along. (should be fixed in the next release of 3.1 and 5.0 RC).

PrintJS as baseline

Fortunately there was already some work done in the PrintJS repository which we could use to wrap a PrintingService around so it’s easier to call from a .NET perspective. The good part is that it supports downloading and printing in one go using the native look and feel (see .gif above).

Getting started

Add the NuGet Package

Inject the IPrintingService in program.cs and don’t forget the using statement.

Use the IPrintingService

Make a .pdf file available through the wwwroot folder or a controller action. In this example a folder /docs was added to the wwwroot folder with a file named sample.pdf , but you can also specify a controller action like this:

Caveats

Currently the service only supports .PDF files and not all original options from PrintJSare available (yet) so feel free to create some PR’s and add some functionality where needed.

GitHub

The code is available on the following GitHub Repository.

Going further

In a next post we’ll be going through multiple html to pdf processors to see which one can help us out the most. For example wkhtmltopdf, razor light, etc. If you have some experience with generating .pdf files make sure to leave a comment!

Turning coffee into code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store