使用 IRONPDF

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

已更新 2024年2月25日
分享:

.NET MAUI 是新一代 .NET,讓開發者能夠使用單一程式碼庫構建跨平台桌面、網頁和行動應用,包括 Xamarin.Forms。 .NET MAUI您可以一次撰寫您的應用程式,並將其部署到多個平台,包括 Windows、macOS、iOS、Android 和 tvOS,且使用相同的專案名稱。.NET MAUI 還允許您在每個平台上利用最新的 UI 功能,例如 macOS 上的深色模式和觸控支援,或 Windows 10 上的語音識別。

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


IronPDF: 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. 在 Visual Studio 中運行的 .NET MAUI 應用程序

第一步:安裝 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 標籤控制項建立一個帶有 "Enter URL to Convert 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" />
XML

HTML to PDF版面設計

為了 HTML to 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" />
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" />
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

第三步:編寫保存和查看 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
VB   C#

需要為每個打算支持的平台實現保存和查看功能 (例如,適用於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
VB   C#

對於 Android 和 macOS,您必須創建具有相同 SaveAndView 實現的單獨文件。您可以從這裡獲取一個可行的示例 GitHub 資料庫.

第四步:PDF 功能的代碼

現在是時候編寫 PDF 功能的代碼了。讓我們從 URL 轉換為 PDF 功能開始。

URL to PDF 功能

創建一個 UrlToPdf 函數,用於 URL 到 PDF 的功能。在函數內實例化 ChromePdfRenderer 物件並使用 RenderUrlAsPdf ``plaintext 將 URL 轉換為 PDF 文件的函式。RenderUrlAsPdf函數從網頁伺服器取得 URL 的資料並處理轉換成 PDF 文件。在參數中,傳遞 URL 輸入控制中的文本,創建SaveService類的對象並使用SaveAndView函數。在SaveAndView` 函數的參數中,傳遞生成的 PDF 文件的流。

SaveAndView 函數幫助在任何自訂路徑保存文件並提供查看 PDF 文件的選項。最後,顯示一個提示框,告知有關 PDF 文件創建的信息。如果使用者嘗試在空輸入控制下創建 PDF 文件,將顯示一個帶有錯誤消息和警告的提示框。


```cs
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");
    }

}

HTML 轉換成 PDF 功能

要進行 HTML 轉換成 PDF 功能,請創建 HtmlToPdf 函數並使用 RenderHtmlAsPdf 函數。使用編輯器控件的文本並將其傳遞給 RenderHtmlAsPdf 函數的參數。類似於上述函數,使用 SaveAndView 函數來啟用保存後查看 PDF 文件的功能。

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文件到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
VB   C#

輸出

運行專案後,輸出將如下所示。

如何在 .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 Viewer 彈出視窗

需要對所有其他功能採用相同的程序。查看此 博客 了解更多有關 IronPDF 在 Blazor 中工作的資訊。

了解如何將 MAUI 頁面作為 XAML 轉換為 PDF 文件,請訪問 "如何在MAUI中將XAML轉換成PDF"."

總結

本教程使用IronPDF在.NET MAUI應用中創建了PDF文件和PDF查看器。.NET MAUI是一個偉大的工具,能夠用單一代碼庫創建跨平台應用程序。IronPDF幫助在任何.NET應用中輕鬆創建和自定義PDF文件。IronPDF與.NET MAUI平台完全兼容。

IronPDF在開發過程中是免費的。你可以得到一個 免費試用密鑰 在生產環境中測試 IronPDF。更多資訊,請訪問 以下連結.

< 上一頁
在 C# 中將 PPT (PowerPoint) 轉換為 PDF(示例教程)
下一個 >
使用 IronPDF 的 C# 中 PDFium 替代方案

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >