Printing PDF’s in Blazor

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…

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

Install-Package Append.Blazor.Printing
//using Append.Blazor.Printingbuilder.Services.AddScoped<IPrintingService, PrintingService>();
@using Append.Blazor.Printing
@inject IPrintingService PrintingService
<button @onclick="@(()=> PrintingService.Print("docs/sample.pdf"))">
Print PDF
</button>
public IActionResult Get()
{
var stream = new FileStream(@"path\to\file", FileMode.Open);
return File(stream, "application/pdf", "FileDownloadName.pdf");
}

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!

--

--

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