跳過到頁腳內容
使用IRONPDF

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

.NET MAUI 是下一代 .NET,讓開發者可以用單一代碼庫構建跨平台的桌面、網頁和移動應用程序,包括 Xamarin.Forms。 使用.NET MAUI,你可以寫一次代碼,將應用部署到多個平台,包括 Windows、macOS、iOS、Android 和 tvOS,而使用相同的項目名稱。 .NET MAUI 還能讓你利用每個平台的最新 UI 能力,如 macOS 的深色模式和觸摸支持,或 Windows 10 的語音識別。

本文將解釋如何在 .NET MAUI 應用程序中使用 IronPDF 來創建具有諸多優勢的 PDF 文件。


class="hsg-featured-snippet">

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

  1. 安裝 IronPDF 以查看 .NET MAUI 中的 PDF 文件
  2. 設置 MAUI 項目的前端設計
  3. 處理本地存儲中的文件保存並查看 PDF
  4. 使用 URL、HTML 字符串或文件的渲染方法
  5. 將渲染的 PDF 傳遞給步驟 3 中的自定義處理程序

IronPDF:C# PDF 文庫

IronPDF 是一個 .NET 庫,允許你生成和編輯 PDF 文件。 它非常適合用於 .NET MAUI 應用程序,因為它提供了一系列功能,可以根據你的具體需求進行定制。 IronPDF 的易於使用API,使得將 PDF 功能集成到 .NET MAUI 項目中變得簡單。

先决条件

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

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

步驟 1:安裝 IronPDF

使用 Visual Studio 的 NuGet Package Manager Console 安裝 IronPDF 到新項目中是最佳方式之一。 使用這種方法安裝 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"。 之後,應用水平堆疊佈局以水平排列 Entry 控件和按鈕。 然後在控件之後放置一條線,將下一組控件隔開。

<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,僅添加一個按鈕。 該按鈕將幫助使用 IronPDF 將 HTML 文件轉換為 PDF 文件。

<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的局部空函數,具有三個參數:文件名、文件類型、用於寫入文件的內存流。

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 查看器 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函數從 web 服務器獲取 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 功能

創建FileToPdf函數用於轉換 HTML 文件到 PDF 文件。 使用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:輸出 輸出

在此區段放入 Microsoft 網站 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 查看器彈出窗口

需要對所有其他功能執行相同的程序。 查看這篇IronPDF on Blazor 博客文章,了解更多關於 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 檢視器工具儲存和顯示這些 PDF 檔案。

在 .NET MAUI 中設定 IronPDF 需要哪些步驟?

為 .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嗎?

是的,您可以使用 IronPDF 的RenderHtmlAsPdf方法在 .NET MAUI 應用程式中將 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?

您可以使用 IronPDF 的免費開發許可證,在您的 .NET MAUI 專案中進行測試。這樣,您就可以在購買完整生產許可證之前,將 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。