跳至页脚内容
使用IRONPDF

如何在.NET MAUI中查看PDF(逐步)教程

.NET MAUI 是.NET的下一代,它使开发人员能够用一个代码库构建跨平台的桌面、Web和移动应用程序,包括Xamarin.Forms。 使用 .NET MAUI,您可以编写一次应用程序,并将其部署到多个平台,包括Windows、macOS、iOS、Android和tvOS,项目名称相同。 .NET MAUI 还使您能够利用每个平台的最新UI功能,例如macOS上的暗黑模式和触摸支持,或Windows 10上的语音识别。

本文将解释如何在.NET MAUI应用程序中使用IronPDF来创建具有诸多优势的PDF文档。

<hr

class="hsg-featured-snippet">

如何在.NET MAUI中查看PDF文件

  1. 安装IronPDF以查看.NET MAUI中的PDF文件
  2. 设置MAUI项目的前端设计
  3. 处理将文件保存到本地存储并查看PDF
  4. 使用渲染方法处理URL、HTML字符串或文件
  5. 将呈现的PDF传递给第3步中的自定义处理程序

探索 IronPDF 用于 PDF 管理 是一个为使用 C# 编程语言的开发人员提供的工具,允许他们在其应用程序内部直接创建、读取和编辑 PDF 文档。

IronPDF是一个.NET库,允许您生成和编辑PDF文件。 它非常适合在.NET MAUI应用程序中使用,因为它提供了一系列功能,可以根据您的具体需求进行定制。 凭借其易于使用的API,IronPDF使您可以简单地将PDF功能集成到.NET MAUI项目中。

前提条件

在.NET MAUI中使用IronPDF创建PDF和PDF查看器有一些先决条件:

  1. 最新版本的Visual Studio
  2. .NET Framework 6或7
  3. 在Visual Studio中安装的MAUI包
  4. .NET MAUI应用程序在Visual Studio中运行

步骤1:安装IronPDF

在新项目中安装IronPDF的最佳方法之一是在Visual Studio中使用NuGet包管理器控制台。 使用这种方法安装IronPDF有一些优势。

  • 它很容易操作,并且
  • 您可以确保使用的是IronPDF的最新版本。

安装IronPDF的步骤

首先,通过导航到工具 > NuGet包管理器 > 包管理器控制台打开包管理器控制台。

如何在.NET MAUI中查看PDF(逐步)教程,图1:包管理器控制台 包管理器控制台

接下来,输入以下命令:

Install-Package IronPdf

这将安装该包及其所有依赖项,如assets文件夹。

如何在.NET MAUI中查看PDF(逐步)教程,图2:IronPDF安装 IronPDF安装

您现在可以在您的MAUI项目中开始使用IronPDF。

步骤2:设置.NET MAUI中的前端设计

首先,为IronPDF的三个功能创建一个布局。

URL到PDF布局

对于URL到PDF布局,使用.NET MAUI标签控件创建一个文本为"输入URL以转换为PDF"的标签。 之后,应用一个水平堆栈布局,以水平排列条目控件和按钮。 然后在控件后放置一条线,以分隔下一部分控件。

<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 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到PDF布局

对于HTML到PDF部分的布局,创建一个编辑器控件和一个按钮。 编辑器控件将用于接受用户提供的HTML内容字符串。 另外,添加一条线作为分隔符。

<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="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文件到PDF布局

对于HTML文件到PDF,只需添加一个按钮。 该按钮将帮助将HTML文件转换为PDF文档,使用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" />
<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

完整的UI代码

下面提供了.NET MAUI前端的完整源代码。

<?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 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

步骤3:保存和查看PDF文件的代码

.NET MAUI没有任何用于在本地存储中保存文件的预构建功能。 因此,必须自行编写代码。 为创建保存和查看功能,创建一个名为SaveService的部分类,定义一个名为SaveAndView的部分void函数,具有三个参数:文件名、文件内容类型和用于写入文件的内存流。

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
$vbLabelText   $csharpLabel

保存和查看功能需要为每个平台实现,例如Android、macOS或Windows。 对于Windows平台,创建一个名为"SaveWindows.cs"的文件,并实现部分方法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
$vbLabelText   $csharpLabel

对于Android和macOS,您需要创建具有类似SaveAndView实现的单独文件。 可以从这个MAUI PDF Viewer GitHub仓库获取一个工作示例。

步骤4:PDF功能代码

现在,是编写PDF功能代码的时候了。 让我们从URL到PDF功能开始。

URL到PDF功能

创建一个UrlToPdf函数用于URL到PDF功能。 Inside the function, instantiate the ChromePdfRenderer object and use the RenderUrlAsPdf function to convert the URL to PDF documents. RenderUrlAsPdf函数从网络服务器获取URL数据并处理它以转换为PDF文档。 在参数中,传递URL条目控件中的文本,创建SaveService类的对象,并使用SaveAndView函数。 在SaveAndView函数的参数中,传入生成的PDF文件的流。

SaveAndView函数有助于在任何自定义路径上保存文件,并提供查看PDF文件的选项。 最后,显示一个通知框,告知创建PDF文件的状态。如果用户尝试使用空条目控件创建PDF文件,将显示一个带有错误消息和警告的通知框。

private void UrlToPdf(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(URL.Text))
    {
        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 (!string.IsNullOrEmpty(URL.Text))
    {
        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 Not String.IsNullOrEmpty(URL.Text) 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
$vbLabelText   $csharpLabel

HTML到PDF功能

为HTML到PDF功能,创建HtmlToPdf函数,并使用RenderHtmlAsPdf函数。 使用编辑器控件中的文本,并在RenderHtmlAsPdf函数的参数中传入。 与上述功能类似,使用SaveAndView函数,使保存后的PDF文件添入查看功能。

private void HtmlToPdf(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(HTML.Text))
    {
        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 (!string.IsNullOrEmpty(HTML.Text))
    {
        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 Not String.IsNullOrEmpty(HTML.Text) 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
$vbLabelText   $csharpLabel

HTML文件到PDF功能

为HTML文件到PDF功能,创建FileToPdf函数。 使用RenderHtmlFileAsPdf函数,并传入HTML文件路径作为参数。 它将所有HTML内容转换为PDF并保存输出文件。

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
$vbLabelText   $csharpLabel

输出

运行项目后,输出将如下所示。

如何在.NET MAUI中查看PDF(逐步)教程,图3:输出 输出

在此部分输入微软网站的URL并点击按钮。

如何在.NET MAUI中查看PDF(逐步)教程,图4:URL到PDF URL到PDF

创建PDF文件后,它显示一个对话框以便将文件保存到定制目标。

如何在.NET MAUI中查看PDF(逐步)教程,图5:保存文件 保存文件

保存文件后,会出现弹出窗口,并提供选择PDF查看器以查看PDF文件的选项。

如何在.NET MAUI中查看PDF(逐步)教程,图6:PDF查看器弹出 PDF查看器弹出

IronPDF出色地将URL转换为PDF。 它保持了所有颜色和图像的原始形状和格式。

如何在.NET MAUI中查看PDF(逐步)教程,图7:PDF查看器弹出 PDF查看器弹出

需要遵循与其他所有功能相同的过程。 查看这篇Blazor Blog Post中的IronPDF,以了解IronPDF在Blazor中的工作方式。

访问"如何在MAUI中将XAML转换为PDF"了解如何将MAUI页面作为XAML转换为PDF文档。

摘要

本教程在.NET MAUI应用程序中使用IronPDF来创建PDF文件和PDF查看器。 .NET MAUI是一个用于通过单一代码库创建多平台应用程序的绝佳工具。 IronPDF帮助在任何.NET应用程序中轻松创建和自定义PDF文件。 IronPDF完全兼容.NET MAUI平台。

IronPDF对开发免费。 您可以获取一个免费试用密钥,来测试IronPDF在生产环境中的使用效果。 有关IronPDF及其功能的更多信息,请访问IronPDF官方网站

常见问题解答

我如何在 .NET MAUI 应用程序中集成 PDF 查看器?

要在 .NET MAUI 应用程序中集成 PDF 查看器,您可以使用 IronPDF 来处理 PDF 文件的渲染和查看。IronPDF 允许您从 URL、HTML 字符串和 HTML 文件中渲染 PDF,然后可以使用 .NET MAUI 中的各种 PDF 查看工具进行保存和显示。

设置 IronPDF for .NET MAUI 的步骤是什么?

为 .NET MAUI 设置 IronPDF 包括通过 Visual Studio 中的 NuGet 包管理器安装 IronPDF 包,配置项目以处理 PDF 渲染,并使用 IronPDF 的方法将 HTML、URL 或 HTML 文件转换为 PDF 文档。

我如何确保我的 PDF 布局在 .NET MAUI 中得到保留?

IronPDF 为在 .NET MAUI 应用程序中保留 PDF 布局提供了强大的功能。通过使用 RenderHtmlAsPdfRenderUrlAsPdf 等方法,您可以在保持原始格式和布局的同时,将内容转换为 PDF。

在 .NET MAUI 中查看 PDF 时常见的问题是什么,如何解决?

在 .NET MAUI 中查看 PDF 时常见的问题包括特定平台的渲染错误和文件访问权限。这些问题可以通过使用 IronPDF 的跨平台功能和确保在应用程序代码库中正确处理文件权限来解决。

我可以在 .NET MAUI 应用程序中将 HTML 内容转换为 PDF 吗?

是的,您可以在 .NET MAUI 应用程序中使用 IronPDF 的 RenderHtmlAsPdf 方法将 HTML 内容转换为 PDF。这允许您高效地将 HTML 字符串转换为格式完整的 PDF 文档。

我如何在 .NET MAUI 中处理文件保存和查看?

在 .NET MAUI 中,您可以使用 IronPDF 生成 PDF 文件,然后使用特定平台的文件处理 API 实现文件保存和查看。IronPDF 支持将 PDF 文件保存到本地存储,然后可以通过 PDF 查看器打开。

IronPDF 是否兼容 .NET MAUI 的所有目标平台?

是的,IronPDF 兼容 .NET MAUI 目标的所有平台,包括 Windows、macOS、iOS、Android 和 tvOS,实现跨这些系统的无缝 PDF 创建和查看体验。

如何在全面部署前测试 .NET MAUI 项目中的 IronPDF?

您可以通过使用免费的开发许可证在 .NET MAUI 项目中测试 IronPDF。这使您可以在签署全生产许可证之前,将 PDF 功能集成到您的应用程序并进行测试。

IronPDF 是否支持 .NET 10?支持 .NET 10 能带来哪些好处?

是的,IronPDF 完全支持 .NET 10。使用 .NET 10 构建应用程序(包括 MAUI、Web、桌面和云应用程序)时,无需任何自定义变通方案即可直接使用。使用 .NET 10 可以让您体验到最新的平台改进、性能提升和更新的 API。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。