Printing a PDF from .NET MAUI Windows Silently

By | December 1, 2023

I had a request recently to print PDFs from .NET MAUI specifically on Windows Desktop. They also had the need to not display a print dialog, and just print to the default printer. This isn’t nearly as easy as it would seem, and there is a lot of conflicting information online about it. I tried a bunch of different options, and this is the one that worked, and it’s a simple implementation. It’s also a solution I haven’t seen much about online so that’s why I want to share.

I tried PDFium but it was complaining that it had a dependency on System.Windows.Forms. I also tried some of the native calls and was able to print a page I created on the fly, but not PDF. What I finally got working was to use the FreeSpire.PDF package, which is a free open source version of the Spire.PDF package.

NOTE: I wasn’t able to get this working on Android, there is an error on loading the PDF file stream into FreeSpire’s PdfDocument. I was not able to try the app out on iOS. This has been verified on Windows only.

I have created a repo here with a working sample: billreiss/mauiSilentPrintPdf (github.com)

In your .NET MAUI project, add the FreeSpire.PDF NuGet package.

We need a PDF file to print. This could come from an API, the documents folder, or in our case I’ll include it as a MAUI Asset in the app. The important thing is that we have a Stream, it doesn’t matter where it comes from. Just grab any sample PDF or go to the repository for this sample and add it to the Resources/Raw folder. The build action should be MAUI Asset.

The code itself is very straightforward, we get the file stream, load the data into a PdfDocument, set any options we want, and then print.

using Spire.Pdf;
using Spire.Pdf.Print;

PdfDocument pdf = new PdfDocument();
var fileName = "sample-pdf-file.pdf";
var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
pdf.LoadFromStream(stream);
PdfPrintSettings settings = new PdfPrintSettings();
settings.Color = false;
pdf.Print(settings);

With no printer name specified, it will print to the default printer. The PdfPrintSettings object has a property where you can explicitly specify the printer name as well as several other options.

Leave a Reply

Your email address will not be published. Required fields are marked *