How to View PDF in .NET MAUI (Step-by-Step) Tutorial

.NET MAUI is the next generation of .NET that enables developers to build cross-platform Desktop, Web, and Mobile apps, including Xamarin forms with a single codebase. With .NET MAUI, you can write your app once and deploy it to multiple platforms, including Windows, macOS, iOS, Android, and tvOS with same project name. .NET MAUI also enables you to take advantage of the latest UI capabilities on each platform, such as dark mode and touch support on macOS, or speech recognition on Windows 10.

In this article, I'll explain how we can use IronPDF in the .NET MAUI app to create PDF documents with many benefits.


IronPDF: C# PDF Library

IronPDF is a .NET library that allows you to generate and edit PDF file. It's perfect for use in .NET MAUI applications, as it offers a wide range of features that can be customized to fit your specific needs. With its easy-to-use API, IronPDF makes it simple to integrate PDF functionality into your .NET MAUI project.

Prerequisites

There are some prerequisites for creating PDF and PDF Viewer in .NET MAUI using IronPDF:

  1. Visual Studio 2022 (the latest Version)
  2. .NET Framework 6 or 7
  3. MAUI packages installed in Visual Studio
  4. .NET MAUI Application running in Visual Studio

Step 1: Install IronPDF

One of the best ways to install IronPDF in a new project is by using NuGet Package Manager Console within Visual Studio. There are some advantages to using this method to install IronPDF.

  • It's easy to do, and
  • You can be sure that you're using the latest version of the IronPDF.

Steps to Install IronPDF

First, open the Package Manager Console by going to Tools > NuGet Package Manager > Package Manager Console.

How to View PDF in .NET MAUI - Figure 1: Package Manager Console

Package Manager Console

Next, type in the following command:

Install-Package IronPdf

This will install the package and all its dependencies like assets folder.

Install-Package IronPdf
How to View PDF in .NET MAUI - Figure 2: IronPDF Installation

IronPDF Installation

You can now start using IronPDF in your MAUI project.

Step 2: Setup Frontend Design in .NET MAUI

I'll create a layout for three functionalities of IronPDF.

URL to PDF Layout

For the URL to PDF layout, I've created a label with the text "Enter URL to Convert PDF" using a .NET MAUI label control. After that, I used a horizontal stack layout for arranging the Entry control and the button in a horizontal way. I put a line after the controls to divide the next section of controls.

<Label
    Text="Enter URL to Convert PDF"
    SemanticProperties.HeadingLevel="Level1"
    FontSize="18"
    HorizontalOptions="Center" 
/>
<HorizontalStackLayout
    HorizontalOptions="Center">
    <Border Stroke="White"
            StrokeThickness="2"
            StrokeShape="RoundRectangle 5,5,5,5"
            HorizontalOptions="Center">
        <Entry
            x:Name="URL"
            HeightRequest="50"
            WidthRequest="300" 
            HorizontalOptions="Center"
        />
    </Border>

    <Button
        x:Name="urlPDF"
        Text="Convert URL to PDF"
        Margin="30,0,0,0"
        Clicked="UrlToPdf"
        HorizontalOptions="Center" />
</HorizontalStackLayout>

<Line Stroke="White" X2="1500" />
XML

HTML to PDF Layout

For the layout of the HTML to PDF section, I created an Editor control and a button. The Editor control will be used for accepting a string of HTML content from the user. I added a line as a divider.

<Label
    Text="Enter HTML to Convert to PDF"
    SemanticProperties.HeadingLevel="Level2"
    FontSize="18"
    HorizontalOptions="Center" />
<Border 
    Stroke="White"
    StrokeThickness="2"
    StrokeShape="RoundRectangle 5,5,5,5"
    HorizontalOptions="Center">

    <Editor
        x:Name="HTML"
        HeightRequest="200"
        WidthRequest="300" 
        HorizontalOptions="Center"
    />

</Border>

<Button
    x:Name="htmlPDF"
    Text="Convert HTML to PDF"
    Clicked="HtmlToPdf"
    HorizontalOptions="Center" />

<Line Stroke="White" X2="1500" />
XML

HTML File to PDF Layout

For the HTML files to PDF, I created only one button. That button will help to convert an HTML file to a PDF document using IronPDF.

<Label
    Text="Convert HTML file to PDF"
    SemanticProperties.HeadingLevel="Level2"
    FontSize="18"
    HorizontalOptions="Center" />

<Button
    x:Name="htmlFilePDF"
    Text="Convert HTML file to PDF"
    Clicked="FileToPdf"
    HorizontalOptions="Center" />
XML

The Complete UI Code

The full source code for the .NET MAUI front end is given 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="PDF_Viewer.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">
            <Label
                Text="Enter URL to Convert PDF"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="18"
                HorizontalOptions="Center" 
            />
            <HorizontalStackLayout
                HorizontalOptions="Center">
                <Border Stroke="White"
                        StrokeThickness="2"
                        StrokeShape="RoundRectangle 5,5,5,5"
                        HorizontalOptions="Center">
                    <Entry
                        x:Name="URL"
                        HeightRequest="50"
                        WidthRequest="300" 
                        HorizontalOptions="Center"
                    />
                </Border>

                <Button
                    x:Name="urlPDF"
                    Text="Convert URL to PDF"
                    Margin="30,0,0,0"
                    Clicked="UrlToPdf"
                    HorizontalOptions="Center" />
            </HorizontalStackLayout>

            <Line Stroke="White" X2="1500" />

            <Label
                Text="Enter HTML to Convert to PDF"
                SemanticProperties.HeadingLevel="Level2"
                FontSize="18"
                HorizontalOptions="Center" />
            <Border 
                Stroke="White"
                StrokeThickness="2"
                StrokeShape="RoundRectangle 5,5,5,5"
                HorizontalOptions="Center">

                <Editor
                    x:Name="HTML"
                    HeightRequest="200"
                    WidthRequest="300" 
                    HorizontalOptions="Center"
                />

            </Border>

            <Button
                x:Name="htmlPDF"
                Text="Convert HTML to PDF"
                Clicked="HtmlToPdf"
                HorizontalOptions="Center" />

            <Line Stroke="White" X2="1500" />

            <Label
                Text="Convert HTML file to PDF"
                SemanticProperties.HeadingLevel="Level2"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="htmlFilePDF"
                Text="Convert HTML file to PDF"
                Clicked="FileToPdf"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>
XML

Step 3: Code for Save and View PDF file

.NET MAUI doesn't have any pre-built function to save files in local storage. So, we'll need to write the code ourselves. For creating the save and view functionality, I created a partial class named SaveService and a partial void function named SaveAndView with three parameters. In parameters, I passed the file name, file content type, and memory stream to write the file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PDF_Viewer
{
    public partial class SaveService
    {
            public partial void SaveAndView(string filename, string contentType, MemoryStream stream);
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PDF_Viewer
{
    public partial class SaveService
    {
            public partial void SaveAndView(string filename, string contentType, MemoryStream stream);
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks

Namespace PDF_Viewer
	Partial Public Class SaveService
			Public Partial Private Sub SaveAndView(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
			End Sub
	End Class
End Namespace
VB   C#

Saving and viewing functionality will need to be implemented for each platform that we intend to support (e.g. for Android, macOS, and/or Windows). For the Windows platform, create a file named "SaveWindows.cs" and implement the partial method SaveAndView:

using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;

namespace PDF_Viewer
{
    public partial class SaveService
    {
        public async partial void SaveAndView(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.
                    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 PDF_Viewer
{
    public partial class SaveService
    {
        public async partial void SaveAndView(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.
                    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 PDF_Viewer
	Partial Public Class SaveService
		Public Async Sub SaveAndView(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#

For Android and macOS, you've to create separate files with comparable SaveAndView implementations. You can get a working example from this GitHub Repo.

Step 4: Code for PDF Functionalities

Now, it's time to write code for the PDF functionalities. Let's start with URL to PDF functionality.

URL to PDF Functionality

I created a UrlToPdf function for the URL to PDF functionality. Inside the function, I instantiated the ChromePDFRenderer object and I use the RenderUrlAsPdf function to convert the URL to PDF documents. The RenderUrlAsPdf function gets the data of the URL from the web server and processes it to convert it into PDF document. In parameters, I pass the text in URL entry control. I created an object of SaveService class and use the SaveAndView function. In the parameters of the SaveAndView function, I use the stream of the generated PDF file.

The SaveAndView function helps to save files at any customized path and gives the option to view PDF files. At last, I display an alert box with information about creating the PDF file. If a user tries to create a PDF file with empty entry control, it'll display an alert box with an error message and warning.

private void UrlToPdf(object sender, EventArgs e)
{
if (URL.Text != null)
{
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderUrlAsPdf(URL.Text.Trim());
            SaveService saveService = new SaveService();
            saveService.SaveAndView("URLtoPDF.pdf", "application/pdf", pdf.Stream);
            DisplayAlert("Success", "PDF from URL Created!", "OK");
        }
else
{
            DisplayAlert("Error", "Field can't be empty! \nPlease enter URL!", "OK");
        }

    }
private void UrlToPdf(object sender, EventArgs e)
{
if (URL.Text != null)
{
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderUrlAsPdf(URL.Text.Trim());
            SaveService saveService = new SaveService();
            saveService.SaveAndView("URLtoPDF.pdf", "application/pdf", pdf.Stream);
            DisplayAlert("Success", "PDF from URL Created!", "OK");
        }
else
{
            DisplayAlert("Error", "Field can't be empty! \nPlease enter URL!", "OK");
        }

    }
Imports Microsoft.VisualBasic

Private Sub UrlToPdf(ByVal sender As Object, ByVal e As EventArgs)
If URL.Text IsNot Nothing Then
			Dim Renderer = New IronPdf.ChromePdfRenderer()
			Dim pdf = Renderer.RenderUrlAsPdf(URL.Text.Trim())
			Dim saveService As New SaveService()
			saveService.SaveAndView("URLtoPDF.pdf", "application/pdf", pdf.Stream)
			DisplayAlert("Success", "PDF from URL Created!", "OK")
Else
			DisplayAlert("Error", "Field can't be empty! " & vbLf & "Please enter URL!", "OK")
End If

End Sub
VB   C#

HTML to PDF Functionality

For converting HTML to PDF functionality, I created the HtmlToPdf function and use the RenderHtmlAsPdf function. I use the text of Editor control and pass it in the parameters of the RenderHtmlAsPdf function. And similar to the above function, I use the SaveAndView function to enable the functionality to view the PDF file after saving.

private void HtmlToPdf(object sender, EventArgs e)
    {
        if (HTML.Text != null)
        {
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderHtmlAsPdf(HTML.Text);
            SaveService saveService = new SaveService();
            saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", pdf.Stream);
            DisplayAlert("Success", "PDF from HTML Created!", "OK");
        }
        else
        {
            DisplayAlert("Error", "Field can't be empty! \nPlease enter valid HTML!", "OK");
        }
    }
private void HtmlToPdf(object sender, EventArgs e)
    {
        if (HTML.Text != null)
        {
            var Renderer = new IronPdf.ChromePdfRenderer();
            var pdf = Renderer.RenderHtmlAsPdf(HTML.Text);
            SaveService saveService = new SaveService();
            saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", pdf.Stream);
            DisplayAlert("Success", "PDF from HTML Created!", "OK");
        }
        else
        {
            DisplayAlert("Error", "Field can't be empty! \nPlease enter valid HTML!", "OK");
        }
    }
Imports Microsoft.VisualBasic

Private Sub HtmlToPdf(ByVal sender As Object, ByVal e As EventArgs)
		If HTML.Text IsNot Nothing Then
			Dim Renderer = New IronPdf.ChromePdfRenderer()
			Dim pdf = Renderer.RenderHtmlAsPdf(HTML.Text)
			Dim saveService As New SaveService()
			saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", pdf.Stream)
			DisplayAlert("Success", "PDF from HTML Created!", "OK")
		Else
			DisplayAlert("Error", "Field can't be empty! " & vbLf & "Please enter valid HTML!", "OK")
		End If
End Sub
VB   C#

HTML File to PDF Functionality

I created the FileToPDF function for converting HTML files to PDF files. I use the RenderHtmlFileAsPdf function and pass the HTML file path as a parameter. It converts all HTML content into PDF and saves the output file.

private void FileToPdf(object sender, EventArgs e)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var pdf = Renderer.RenderHtmlFileAsPdf(@"C:\Users\Administrator\Desktop\index.html");
        SaveService saveService = new SaveService();
        saveService.SaveAndView("HTML File to PDF.pdf", "application/pdf", pdf.Stream);
        DisplayAlert("Success", "PDF from File Created!", "OK");
    }
private void FileToPdf(object sender, EventArgs e)
    {
        var Renderer = new IronPdf.ChromePdfRenderer();
        var pdf = Renderer.RenderHtmlFileAsPdf(@"C:\Users\Administrator\Desktop\index.html");
        SaveService saveService = new SaveService();
        saveService.SaveAndView("HTML File to PDF.pdf", "application/pdf", pdf.Stream);
        DisplayAlert("Success", "PDF from File Created!", "OK");
    }
Private Sub FileToPdf(ByVal sender As Object, ByVal e As EventArgs)
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim pdf = Renderer.RenderHtmlFileAsPdf("C:\Users\Administrator\Desktop\index.html")
		Dim saveService As New SaveService()
		saveService.SaveAndView("HTML File to PDF.pdf", "application/pdf", pdf.Stream)
		DisplayAlert("Success", "PDF from File Created!", "OK")
End Sub
VB   C#

Output

After running the project, the output will look like this.

How to View PDF in .NET MAUI - Figure 3: Output

Output

I put the Microsoft website URL in this section and click on the button.

How to View PDF in .NET MAUI - Figure 4: URL to PDF

URL to PDF

After creating the PDF file, it shows a dialog box to save the file on the customized destination.

How to View PDF in .NET MAUI - Figure 5: Save File

Save File

After saving the file, this popup shows and gives the option to select PDF viewer to see the PDF file.

How to View PDF in .NET MAUI - Figure 6: PDF Viewer Popup

PDF Viewer Popup

IronPDF converts the URL to PDF outstandingly. It preserves all colors and images in their original shape and formatting.

How to View PDF in .NET MAUI - Figure 7: PDF Viewer Popup

URL to PDF Output

The same procedure needs to be followed with all other functionalities. Check out this blog to learn more about IronPDF's working in Blazor.

Learn how to convert MAUI page as XAML to a PDF document by visiting "How to Convert XAML to PDF in MAUI".

Summary

I use IronPDF in the .NET MAUI app to create a PDF file and PDF viewer. The .NET MAUI is a great tool to create multi-platform applications with a single codebase. IronPDF helps to create and customize PDF files easily in any .NET application. IronPDF is fully compatible with the .NET MAUI platform.

IronPDF is free for development. You can get a free trial key to test IronPDF in production. For more information, visit the following link.