USING IRONPDF

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

Updated February 25, 2024
Share:

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

This article will explain how to 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 files. 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. The latest version of Visual Studio
  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 (Step-by-Step) Tutorial, 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.

How to View PDF in .NET MAUI (Step-by-Step) Tutorial, Figure 2: IronPDF Installation IronPDF Installation

You can now start using IronPDF in your MAUI project.

Step 2: Setup Frontend Design in .NET MAUI

Firstly, create a layout for three functionalities of IronPDF.

URL to PDF Layout

For the URL to PDF layout, create a label with the text "Enter URL to Convert PDF" using a .NET MAUI label control. After that, apply a horizontal stack layout for arranging the Entry control and the button horizontally. Then 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, create an Editor control and a button. The Editor control will be used for accepting a string of HTML content from the user. Additionally, add 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, add 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, it is necessary to write the code ourselves. For creating the save and view functionality, a partial class named SaveService is created with a partial void function named SaveAndView with three parameters: 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 intends 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 MAUI PDF Viewer 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

Create an UrlToPdf function for the URL to PDF functionality. Inside the function, instantiate the ChromePdfRenderer object and 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 a PDF document. In parameters, pass the text in URL entry control, create an object of the SaveService class and use the SaveAndView function. In the parameters of the SaveAndView function, pass in 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, display an alert box with information about creating the PDF file. If a user tries to create a PDF file with an 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, create the HtmlToPdf function and use the RenderHtmlAsPdf function. Use the text of Editor control and pass it in the parameters of the RenderHtmlAsPdf function. Similar to the above function, 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

Create the FileToPdf function for converting HTML files to PDF files, 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 (Step-by-Step) Tutorial, Figure 3: Output Output

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

How to View PDF in .NET MAUI (Step-by-Step) Tutorial, 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 (Step-by-Step) Tutorial, 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 (Step-by-Step) Tutorial, 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 (Step-by-Step) Tutorial, Figure 7: PDF Viewer Popup PDF Viewer Popup

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

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

Summary

This tutorial used 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 about IronPDF and its capabilities, please visit the IronPDF Official Website.

< PREVIOUS
Convert PPT (PowerPoint) to PDF in C# (Example Tutorial)
NEXT >
PDFium in C# Alternatives Using IronPDF

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >