USING IRONPDF

Creating a PDF file in .NET MAUI Using IronPDF

Updated February 11, 2024
Share:

Introduction

The .NET Multi-platform App UI (.NET MAUI) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML. You can use .NET MAUI to operate on Android, iOS, MacOS, and Windows using a single code base. .NET MAUI is open-source and is an improvement over Xamarin Forms. The UI controls have been rewritten from the ground up for performance and extensibility. Additionally, it has expanded from the mobile platform to include desktop use cases. If you've ever used Xamarin Forms to create cross-platform user interfaces, then you'll find that the .NET MAUI framework has a lot in common with it.

However, there are some differences. You can construct multi-platform apps with the .NET MAUI Framework using a single project, but you can add platform-specific code and resources if needed. One of the main goals of .NET MAUI is to allow you to write as much of your app logic and UI layout in a single code base as possible. .NET MAUI will be available for all platforms and will support the existing MVVM and XAML patterns.

.NET MAUI allows developers to work on various platforms such as mobile development and Windows platforms.

IronPDF Features

IronPDF is a powerful PDF converter that can handle almost any task that a browser can handle. The .NET library for developers makes it simple to create, read, and manipulate PDF files. IronPDF uses the Google Chrome engine to convert HTML to PDF files. Among other web technologies, IronPDF supports HTML, ASPX, Razor Pages, and MVC View. IronPDF supports Microsoft .NET applications (both ASP.NET Web Applications and traditional Windows Applications). IronPDF can also be used to make attractive PDF documents.

IronPDF can create PDF files from HTML files containing JavaScript, CSS, and image files.

Not only can HTML files be converted to PDF, but can also convert image files to PDF.

IronPDF can help to create interactive PDF documents, fill out and submit interactive forms, merge and split PDF documents, extract text and images from PDF documents, search text in PDF documents, rasterize PDF pages to images, convert PDF to HTML, and print PDF documents.

IronPDF can generate a document from a URL. For login behind HTML login forms, it also allows the use of custom network login credentials, user agents, proxies, cookies, HTTP headers, and form variables.

IronPDF is a library that can read and fill in PDF documents and is capable of extracting images from documents. It allows us to add headers, footers, text, photos, bookmarks, watermarks, and more to documents. It also allows us to join and split pages in a new or existing document. IronPDF is capable of converting documents to PDF objects without using an Acrobat viewer. It is also possible to convert a CSS file to a PDF document and CSS media-type files can be converted into documents.

Creating a New Project in Visual Studio

Firstly, create a project using both Visual Studio Code and Visual Studio. When using Visual Studio Code, it is necessary to use the command-line tool to install the project type template.

Open the Microsoft Visual Studio software and go to the File menu. Select "new project", and in the new project window select ".NET MAUI App". This article will use a .NET MAUI App to generate PDF documents and save them to a suitable location.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 1: Create a new project in Visual Studio Create a new project in Visual Studio

Enter the project name and select the file path in the appropriate text box. Then, click the Create button, as in the screenshot below.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 2: Configure the project Configure the project

The Visual Studio project will now generate the structure for the selected application following the .NET MAUI App platform, it will now open the MainPage.cs file to add the code and build/run the application.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 3: Adding code into the MainPage.cs file Adding code into the MainPage.cs file

Next, install the library to test the code.

Install the IronPDF Library

The IronPDF Library can be downloaded and installed in four ways.

These are:

  • Using Visual Studio.
  • Using the Visual Studio Command-Line.
  • Direct download from the NuGet website.
  • Direct download from the IronPDF website.

Using Visual Studio

The Visual Studio software provides the NuGet Package Manager option to install the package directly to the solution. The below screenshot shows how to open the NuGet Package Manager.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 4: Navigate to NuGet Package Manager UI Navigate to NuGet Package Manager UI

This provides the search box to show the list of packages from the NuGet website. In the NuGet Package Manager, search for the keyword "IronPDF," as in the screenshot below.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 5: Select IronPdf package from NuGet Package Manager UI IronPdf package from NuGet Package Manager UI

In the above image, the related search items are listed, select the first option to install the package to the solution. It will be installed on all the .NET MAUI application platforms such as the Android, iOS, and Windows platforms.

Using the Visual Studio Command-Line

In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console

Enter the following line in the Package Manager Console tab:

Install-Package IronPdf

Now, the package will download/install to all the .NET MAUI platforms on the current project and be ready to use.

Creating a PDF file in .NET MAUI Using IronPDF, Figure 6: Install the package in the Package Manager Console Install the package in the Package Manager Console

Direct Download from the NuGet Website

The third way is to download the NuGet package directly from their website by accessing this IronPdf package link to go to the NuGet IronPDF repository page.

  • Select the download package option from the menu on the right-hand side.
  • Double-click the downloaded package. It will be installed automatically.
  • Reload the solution and the package should be usable in your project.

Direct Download from the IronPDF Website

Click the link to download the latest zip file directly from the website. Once downloaded, follow the steps below to add the package to your project.

  • Right-click the Dependencies option for the project from the solution window.
  • Select the specific platform, then select the options reference and browse the location of the downloaded reference.
  • Click OK to add the reference.

You will also need to add references to all the .NET MAUI-supported platforms.

Create PDFs on a .NET MAUI app using IronPDF

When a project is created, there will be an auto-generated file called MainPage.xaml. This is where to put the UI of the .NET MAUI application.

Follow the code 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 .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

Once the above code is added to the MainPage.xaml file, open the MainPage.xaml.cs file and include the following method inside of 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 users' computer at a specified location.

In the method above, a new ChromePdfRenderer object is created and invokes the RenderHtmlAsPdf method to produce a new PDF document containing the words "Hello IronPDF! ..." from a string of HTML markup. Next, it will be delegated the saving of the file on the user's device to a separate class, called SaveService. This class will be created in the next step.

The complete MainPage.xaml.cs file is given below. Please ensure that the file contents match what's shown below before continuing to the next step:


// 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#

Now, 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#

Since the implementation details for saving content on user devices vary with each platform (Windows, Android, MacOS, etc), it is necessary to write platform-specific code for each device type that the application will support. To make this possible, we define SaveService as a partial class (for abstraction purposes) containing one partial method, called SaveAndView. Following this, the implementation of this method will be defined in a separate SaveService.cs partial class for one or more of the folders nested in the Platforms folder within the Solutions Explorer (see image below):

Creating a PDF file in .NET MAUI Using IronPDF, Figure 7: The folder structure to implement cross-platforms The folder structure to implement cross-platform

For simplicity, this tutorial will define the aforementioned partial file for the Windows platform only. Create a new SaveService.cs file under the Windows platform folder containing the code shown below:

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();
            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.
                using 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();
            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.
                using 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.
					Using 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
				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:

Creating a PDF file in .NET MAUI Using IronPDF, Figure 8: The UI of the MAUI App The UI of the MAUI App

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

Creating a PDF file in .NET MAUI Using IronPDF, Figure 9: Select a location to save the PDF file Select a location to save the PDF file

Conclusion

IronPDF is one of the most commonly used PDF converter libraries that allows you to generate, read, edit, and format PDFs. The IronPDF library provides many benefits and functionality, including a browser engine that will help to convert a given URL into a PDF file, allows you to add CSS to HTML strings and convert them to PDF files, and also allows you to fill out PDF forms. All of the features of IronPDF are included in one library.

IronPDF comes with various price structures. The basic price for IronPDF starts at $749. Product support and updates are also available for a one-year fee. Royalty-free redistribution coverage can also be purchased as an add-on.

To summarize, IronPDF is recommended since it offers great performance and a large number of features for developers working with PDFs. It supports universal platforms such as .NET MAUI. It also comes with excellent assistance and documentation, allowing you to fully utilize the wide range of the IronPDF library and its many features.

< PREVIOUS
Create a PDF File with Blazor Tutorial
NEXT >
How to Convert Image to PDF in C# [Code Example Tutorial]

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >