Create .NET MAUI PDF Document using Visual Studio

Introduction

A framework for building native mobile and desktop applications with C# and XAML is called the .NET Multi-platform App UI (.NET MAUI). .NET MAUI is the next generation framework for .NET Core and .NET Framework. It allows .NET application developers to create applications for desktop, web, and mobile platforms with common UI components using a single codebase. MAUI also allows you to add platform-specific code and resources, when necessary.

As for creating PDF files/pages in .NET MAUI application, it would likely be possible to use a PDF library like IronPDF to generate PDF documents within a .NET MAUI application.

IronPDF Features

IronPDF is a robust HTML to PDF conversion library that can perform nearly every operation a browser can. It can be used to create, and edit existing PDFs within .NET applications, as well as perform other common PDF data operations. IronPDF allows you to generate PDF versions of complex web pages that make heavy use of CSS and JavaScript for layout and interactivity. To use IronPDF to generate a PDF from HTML, you can load the HTML into a string or stream and pass it to the IronPDF library, which will convert it to a PDF document. You can then save the PDF to a file, stream, or other output destination.

As a general-purpose library, IronPDF can be used in any .NET application. This article will show how IronPDF can be used in applications built with .NET MAUI.

Prerequisites

We can generate PDF files using IronPDF from HTML files that contain JavaScript, CSS, and picture files. Here are some prerequisites before starting the work:

  • .NET Framework installed in Visual Studio
  • A running .NET MAUI Blazor app or a simple .NET MAUI project
  • A stable internet to install IronPDF library using Visual Studio Command-line.

.NET MAUI PDF File Creation

  1. In Visual Studio, create a new .NET MAUI PDF project.
  2. Using NuGet, install the IronPDF Library.
  3. Create the .NET MAUI Content Pages' User Interface (UI)
  4. To create a PDF file, use the ChromePdfRenderer.RenderHtmlAsPdf method.
  5. Platform-specific code saves the PDF file to users' devices.

Install the IronPDF Library

Using the Visual Studio Command-Line

To install IronPDF in a .NET application using the NuGet Package Manager, you can follow these steps:

  1. Open the NuGet Package Manager Console in your new project. This can typically be done by going to the "Tools" menu in Visual Studio and selecting "NuGet Package Manager" > "Package Manager Console".
  2. In the NuGet Package Manager Console, run the following command to install IronPDF.

    Install-package IronPdf

    Install IronPDF

This will install the IronPDF library in your .NET application and add it to your project's references within project name.

Create PDF Documents on a .NET MAUI app using IronPDF

When you create a new project in .NET MAUI, an auto-generated file called MainPage.xaml will be created. This file contains the default user interface (UI) design for your application and can be used to customize the appearance and layout of your application's UI. You can edit the MainPage.xaml file to add, remove, or modify UI elements, such as buttons, text boxes, and images, to create the desired bottom up look and feel for your MAUI application.

We will use the XAML markup below.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MAUI_PDF.MainPage"
>
    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">
            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Label
                Text="Welcome to IronPDF!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />
            <Button
                x:Name="PdfBtn"
                Text="Click me to generate PDF"
                SemanticProperties.Hint="Click button to generate PDF"
                Clicked="GeneratePDF"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>
XML

After adding the specified content to the MainPage.xaml file, open the MainPage.xaml.cs file and include the following method and code inside the MainPage class:

private void GeneratePDF(object sender, EventArgs e)
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
    //Saves the memory stream as file.
    SaveService saveService = new SaveService();
    saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
}
private void GeneratePDF(object sender, EventArgs e)
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
    //Saves the memory stream as file.
    SaveService saveService = new SaveService();
    saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
}
Private Sub GeneratePDF(ByVal sender As Object, ByVal e As EventArgs)
	Dim renderer As New ChromePdfRenderer()
	Dim doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>")
	'Saves the memory stream as file.
	Dim saveService As New SaveService()
	saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream)
End Sub
VB   C#

The GeneratePDF method generates a new PDF document containing the text "Hello IronPDF!..." and saves it on the user's computer at a specified location. This is achieved by creating a new ChromePdfRenderer object and invoking the RenderHtmlAsPdf method to convert a string of HTML markup into a PDF document. The PDF is then saved to the user's device using a separate class called SaveService, which we will create in the next step. The complete MainPage.xaml.cs file with the GeneratePDF method is provided below for reference.

// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF;    
// This namespace is required to make use of IronPDF functionality
using IronPdf;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private void GeneratePDF(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
        //Saves the memory stream as file.
        SaveService saveService = new SaveService();
        saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
    }
}
// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF;    
// This namespace is required to make use of IronPDF functionality
using IronPdf;
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }
    private void GeneratePDF(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
        //Saves the memory stream as file.
        SaveService saveService = new SaveService();
        saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
    }
}
Imports IronPdf

' Change the namespace as desired, but make sure that all source files use this same namespace,
' or there will be errors!
Namespace MAUI_IronPDF
	' This namespace is required to make use of IronPDF functionality
	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub GeneratePDF(ByVal sender As Object, ByVal e As EventArgs)
			Dim renderer As New ChromePdfRenderer()
			Dim doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>")
			'Saves the memory stream as file.
			Dim saveService As New SaveService()
			saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream)
		End Sub
	End Class
End Namespace
VB   C#

To save the generated PDF to the user's device, create a new class file called SaveService.cs in the root of the project and add the following source code:

// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF
{
    // SaveService partial class declaration ... this allows a layer of abstraction
    // as we implement the save file details specially for each platform on which this app will
    // operate! 
    public partial class SaveService
    {
        public void SaveAndView(string filename, string contentType, MemoryStream stream)
        {
            SaveFile(filename, contentType, stream);
        }
        // Additional partial files will provide implementations for this method specifically.
        partial void SaveFile(string filename, string contentType, MemoryStream stream);
    }
}
// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF
{
    // SaveService partial class declaration ... this allows a layer of abstraction
    // as we implement the save file details specially for each platform on which this app will
    // operate! 
    public partial class SaveService
    {
        public void SaveAndView(string filename, string contentType, MemoryStream stream)
        {
            SaveFile(filename, contentType, stream);
        }
        // Additional partial files will provide implementations for this method specifically.
        partial void SaveFile(string filename, string contentType, MemoryStream stream);
    }
}
' Change the namespace as desired, but make sure that all source files use this same namespace,
' or there will be errors!
Namespace MAUI_IronPDF
	' SaveService partial class declaration ... this allows a layer of abstraction
	' as we implement the save file details specially for each platform on which this app will
	' operate! 
	Partial Public Class SaveService
		Public Sub SaveAndView(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
			SaveFile(filename, contentType, stream)
		End Sub
		' Additional partial files will provide implementations for this method specifically.
		Partial Private Sub SaveFile(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
		End Sub
	End Class
End Namespace
VB   C#

In order to save the generated PDF on the user's device, we need to write platform-specific code for each type of device that the application supports. To make this possible, we define SaveService as a partial class containing a partial method called SaveAndView. The implementation of this method will be defined in a separate SaveService.cs partial classes for each supported platform, which are located in the nested folders within the Platforms folder in the Solutions Explorer (as shown in the image below). This allows us to write platform-specific code to handle the details of saving content on user devices.

Different Platforms

To keep things simple, this tutorial will only define the SaveService.cs partial file for the Windows platform. To do this, create a new SaveService.cs file under the Windows platform folder and add the following code:

using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace MAUI_IronPDF;
public partial class SaveService
{
    async partial void SaveFile(string filename, string contentType, MemoryStream stream)
    {
        StorageFile stFile;
        string extension = Path.GetExtension(filename);
        //Gets process windows handle to open the dialog in application process. 
        IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
        {
            //Creates file save picker to save a file. 
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.DefaultFileExtension = ".pdf";
            savePicker.SuggestedFileName = filename;
            //Saves the file as PDF file.
            savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
            WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
            stFile = await savePicker.PickSaveFileAsync();
        }
        else
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;
            stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        }
        if (stFile != null)
        {
            using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                //Writes compressed data from memory to file.
                Stream outstream = zipStream.AsStreamForWrite();
                outstream.SetLength(0);
                //Saves the stream as file.
                byte[] buffer = stream.ToArray();
                outstream.Write(buffer, 0, buffer.Length);
                outstream.Flush();
            }
            //Create message dialog box. 
            MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
            UICommand yesCmd = new("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new("No");
            msgDialog.Commands.Add(noCmd);
            WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
            //Showing a dialog box. 
            IUICommand cmd = await msgDialog.ShowAsync();
            if (cmd.Label == yesCmd.Label)
            {
                //Launch the saved file. 
                await Windows.System.Launcher.LaunchFileAsync(stFile);
            }
        }
    }
}
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace MAUI_IronPDF;
public partial class SaveService
{
    async partial void SaveFile(string filename, string contentType, MemoryStream stream)
    {
        StorageFile stFile;
        string extension = Path.GetExtension(filename);
        //Gets process windows handle to open the dialog in application process. 
        IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
        if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
        {
            //Creates file save picker to save a file. 
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.DefaultFileExtension = ".pdf";
            savePicker.SuggestedFileName = filename;
            //Saves the file as PDF file.
            savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
            WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
            stFile = await savePicker.PickSaveFileAsync();
        }
        else
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;
            stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
        }
        if (stFile != null)
        {
            using (IRandomAccessStream zipStream = await stFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                //Writes compressed data from memory to file.
                Stream outstream = zipStream.AsStreamForWrite();
                outstream.SetLength(0);
                //Saves the stream as file.
                byte[] buffer = stream.ToArray();
                outstream.Write(buffer, 0, buffer.Length);
                outstream.Flush();
            }
            //Create message dialog box. 
            MessageDialog msgDialog = new("Do you want to view the document?", "File has been created successfully");
            UICommand yesCmd = new("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new("No");
            msgDialog.Commands.Add(noCmd);
            WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);
            //Showing a dialog box. 
            IUICommand cmd = await msgDialog.ShowAsync();
            if (cmd.Label == yesCmd.Label)
            {
                //Launch the saved file. 
                await Windows.System.Launcher.LaunchFileAsync(stFile);
            }
        }
    }
}
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI.Popups
Namespace MAUI_IronPDF
	Partial Public Class SaveService
		Private Async Sub SaveFile(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
			Dim stFile As StorageFile
			Dim extension As String = Path.GetExtension(filename)
			'Gets process windows handle to open the dialog in application process. 
			Dim windowHandle As IntPtr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle
			If Not Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then
				'Creates file save picker to save a file. 
				Dim savePicker As New FileSavePicker()
				savePicker.DefaultFileExtension = ".pdf"
				savePicker.SuggestedFileName = filename
				'Saves the file as PDF file.
				savePicker.FileTypeChoices.Add("PDF", New List(Of String)() From {".pdf"})
				WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle)
				stFile = Await savePicker.PickSaveFileAsync()
			Else
				Dim local As StorageFolder = ApplicationData.Current.LocalFolder
				stFile = Await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting)
			End If
			If stFile IsNot Nothing Then
				Using zipStream As IRandomAccessStream = Await stFile.OpenAsync(FileAccessMode.ReadWrite)
					'Writes compressed data from memory to file.
					Dim outstream As Stream = zipStream.AsStreamForWrite()
					outstream.SetLength(0)
					'Saves the stream as file.
					Dim buffer() As Byte = stream.ToArray()
					outstream.Write(buffer, 0, buffer.Length)
					outstream.Flush()
				End Using
				'Create message dialog box. 
				Dim msgDialog As New MessageDialog("Do you want to view the document?", "File has been created successfully")
				Dim yesCmd As New UICommand("Yes")
				msgDialog.Commands.Add(yesCmd)
				Dim noCmd As New UICommand("No")
				msgDialog.Commands.Add(noCmd)
				WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle)
				'Showing a dialog box. 
				Dim cmd As IUICommand = Await msgDialog.ShowAsync()
				If cmd.Label = yesCmd.Label Then
					'Launch the saved file. 
					Await Windows.System.Launcher.LaunchFileAsync(stFile)
				End If
			End If
		End Sub
	End Class
End Namespace
VB   C#

Build and run the MAUI application. A window will appear containing the interface shown below:

MAUI Application Output

Click on the "Generate PDF" button. After a few moments, a popup will appear that allows us to choose the location of the generated PDF file.

Location Popup

Get more tutorials and support resources from the following link.

Conclusion

In conclusion, IronPDF is a powerful and versatile PDF library that works well with .NET MAUI system. IronPDF may be used to combine and divide PDF files, extract text and images from PDF files, search PDF files for text, rasterize pages of PDFs to images, and print PDF files. It can also build interactive PDF documents and fill out interactive forms. Its range of features make it a valuable tool for building cross-platform applications in .NET MAUI.

IronPDF is available at various price points, starting at $749. Product support and updates can also be purchased for an additional fee, as well as royalty-free redistribution coverage as an add-on.