跳過到頁腳內容
使用IRONPDF
如何在 .NET Maui 中查看 PDF 文件

使用IronPDF在.NET MAUI中創建PDF文件

.NET多平台應用程式 UI (.NET MAUI) 是一個跨平台框架,用於使用 C# 和 XAML 建立原生行動和桌面應用程式。 您可以使用.NET MAUI ,透過一套程式碼庫在 Android、iOS、macOS 和 Windows 上運行。 .NET MAUI是開源的,並且比 Xamarin Forms 有所改進。 為了提高效能和可擴展性,使用者介面控制已從頭開始重寫。 此外,它已從行動平台擴展到包括桌面應用場景。 如果您曾經使用 Xamarin Forms 創建跨平台使用者介面,那麼您會發現.NET MAUI框架與它有許多共同之處。

然而,兩者之間也存在一些差異。 使用.NET MAUI框架,您可以使用單一專案建立多平台應用程序,但也可以根據需要添加特定於平台的程式碼和資源。 .NET MAUI的主要目標之一是讓您盡可能在單一程式碼庫中編寫應用程式邏輯和 UI 佈局。 .NET MAUI將適用於所有平台,並將支援現有的 MVVM 和 XAML 模式。

.NET MAUI允許開發人員在各種平台上工作,例如行動開發和 Windows 平台。

IronPDF功能

IronPDF是一款功能強大的 PDF 轉換器,幾乎可以處理瀏覽器能夠處理的任何任務。 面向開發人員的.NET庫使建立、讀取和操作 PDF 檔案變得簡單。 IronPDF使用 Google Chrome 引擎將 HTML 檔案轉換為 PDF 檔案。 IronPDF支援多種 Web 技術,包括 HTML、ASPX、使用IronPDF將Razor頁面轉換為 PDF以及 MVC 視圖。 IronPDF支援 Microsoft .NET應用程式(包括ASP.NET Web 應用程式和傳統 Windows 應用程式)。 IronPDF也可以用來製作美觀的 PDF 文件。

IronPDF可以從包含JavaScript 、CSS 和影像檔案的HTML 檔案建立 PDF 檔案

IronPDF不僅可以將HTML檔案轉換為PDF ,還可以將影像檔案轉換為PDF

IronPDF可以幫助建立互動式 PDF 文檔,使用IronPDF填寫和提交互動式表單合併和拆分 PDF 文檔,從 PDF 文件中提取文字和圖像,在 PDF 文件中搜尋文本,將 PDF 頁面柵格化為圖像,將 PDF 轉換為 HTML,並使用IronPrint列印 PDF 文件

IronPDF可以根據 URL 產生文件。 對於使用IronPDF 的登入表單在 HTML 後進行登錄,它還允許使用自訂網頁登入憑證、使用者代理、代理、cookie、HTTP 標頭和表單變數。

IronPDF是一個可以讀取和填充 PDF 文檔,並能夠從文檔中提取圖像的庫。 它允許我們為 PDF 文件添加頁眉和頁腳、文字、照片、書籤以便於導航、浮水印等。 它還允許我們在新文檔或現有文檔中合併和分割頁面。 IronPDF無需使用 Acrobat 檢視器即可將文件轉換為 PDF 物件。 也可以將 CSS 文件轉換為 PDF 文檔,CSS 媒體類型文件也可以轉換為文檔。

在 Visual Studio 中建立新項目

首先,分別使用 Visual Studio Code 和 Visual Studio 建立一個專案。 使用 Visual Studio Code 時,需要使用命令列工具來安裝專案類型範本。

開啟 Microsoft Visual Studio 軟體,然後前往"檔案"功能表。 選擇"新專案",然後在新專案視窗中選擇".NET MAUI應用程式"。本文將使用.NET MAUI應用程式產生 PDF 文件並將其儲存到適當的位置。

在.NET MAUI中使用IronPDF建立 PDF 文件,圖 1:在 Visual Studio 中建立新專案 在 Visual Studio 中建立一個新項目

請在對應的文字方塊中輸入項目名稱並選擇檔案路徑。 然後,點擊"建立"按鈕,如下圖所示。

在.NET MAUI中使用IronPDF建立PDF文件,圖2:設定項目 配置專案

Visual Studio 專案現在將依照.NET MAUI應用程式平台為選取的應用程式產生結構。 現在它將打開 MainPage.cs 檔案以新增程式碼並建置/運行應用程式。

在.NET MAUI中使用IronPDF建立PDF文件,圖3:在MainPage.cs文件中加入程式碼 在 MainPage.cs 檔案中加入程式碼

接下來,安裝庫以測試程式碼。

安裝IronPDF庫

IronPDF庫可以透過四種方式下載和安裝。

這些都是:

  • 使用 Visual Studio。
  • 使用 Visual Studio 命令列。
  • 直接從NuGet網站下載。
  • 直接從IronPDF網站下載。

使用 Visual Studio

Visual Studio 軟體提供了NuGet套件管理器選項,可以直接將套件安裝到解決方案中。 下面這張截圖展示如何開啟NuGet套件管理器。

在.NET MAUI中使用IronPDF建立PDF文件,圖4:使用NuGet套件管理器UI導航 導航至NuGet套件管理器使用者介面

這將顯示搜尋框,用於查找NuGet網站上的程式包清單。在NuGet套件管理器中,搜尋關鍵字"IronPDF",如下圖所示。

在.NET MAUI中使用IronPDF建立PDF文件,圖5:從NuGet套件管理器UI中選擇IronPDF套件 透過NuGet套件管理器 UI 中的IronPDF包

上圖中列出了相關的搜尋項,選擇第一個選項將軟體包安裝到解決方案中。 它將安裝在所有.NET MAUI應用程式平台上,例如 Android、iOS 和 Windows 平台。

使用 Visual Studio 命令列

在 Visual Studio 中,前往"工具" > "NuGet套件管理員" > "套件管理員控制台"。

在程式包管理器控制台標籤中輸入以下代碼:

Install-Package IronPdf

現在,該軟體包將下載/安裝到目前專案中的所有.NET MAUI平台,即可使用。

在.NET MAUI中使用IronPDF建立PDF文件,圖6:在程式包管理器控制台中安裝程式包 在軟體包管理器控制台中安裝軟體包

直接從NuGet網站下載

第三種方法是透過造訪此連結直接從他們的網站下載NuGet套件IronPDF NuGet repository page

  • 從右側選單中選擇下載套件選項。
  • 雙擊下載的軟體包。 它將自動安裝。
  • 重新載入解決方案後,該軟體包應該就可以在您的專案中使用了。

直接從IronPDF網站下載

直接從IronPDF官網下載最新的 ZIP 軟體包。下載完成後,請按照以下步驟將該軟體包新增至您的專案。

  • 在解決方案視窗中以滑鼠右鍵按一下專案的"依賴項"選項。
  • 選擇特定平台,然後選擇選項參考,並瀏覽下載參考文件的位置。
  • 按一下"確定"以新增引用。

您還需要新增對所有.NET MAUI支援的平台的參考。

使用IronPDF在.NET MAUI應用程式中建立 PDF

建立專案時,會自動產生一個名為 MainPage.xaml 的檔案。 這裡是放置.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="MAUI_PDF.MainPage"
            >

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute .NET bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to IronPDF!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Button
                x:Name="PdfBtn"
                Text="Click me to generate PDF"
                SemanticProperties.Hint="Click button to generate PDF"
                Clicked="GeneratePDF"
                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="MAUI_PDF.MainPage"
            >

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute .NET bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to IronPDF!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Button
                x:Name="PdfBtn"
                Text="Click me to generate PDF"
                SemanticProperties.Hint="Click button to generate PDF"
                Clicked="GeneratePDF"
                HorizontalOptions="Center" />
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>
XML

將上述程式碼加入 MainPage.xaml 文件後,開啟 MainPage.xaml.cs 文件,並在 MainPage 類別中包含以下方法:

private void GeneratePDF(object sender, EventArgs e)
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");

    // Saves the memory stream as file.
    SaveService saveService = new SaveService();
    saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
}
private void GeneratePDF(object sender, EventArgs e)
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();
    var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");

    // Saves the memory stream as file.
    SaveService saveService = new SaveService();
    saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
}
$vbLabelText   $csharpLabel

GeneratePDF 方法產生新的 PDF 文檔,其中包含文字"Hello, IronPDF!...",並將其儲存到使用者電腦上的指定位置。

在上述方法中,建立了一個新的ChromePdfRenderer對象,並調用RenderHtmlAsPdf方法產生一個新的 PDF 文檔,其中包含"Hello IronPDF!" ……從一段 HTML 標記字串中提取。接下來,將文件儲存到使用者裝置上的任務委託給一個名為 SaveService 的單獨類別。該類別將在下一步中建立。

完整的 MainPage.xaml.cs 文件如下所示。 請確保文件內容與下方所示內容一致,然後再進行下一步:

// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF;    

// This namespace is required to make use of IronPDF functionality
using IronPdf;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void GeneratePDF(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
        // Saves the memory stream as file.
        SaveService saveService = new SaveService();
        saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
    }
}
// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF;    

// This namespace is required to make use of IronPDF functionality
using IronPdf;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void GeneratePDF(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();
        var doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>");
        // Saves the memory stream as file.
        SaveService saveService = new SaveService();
        saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream);
    }
}
$vbLabelText   $csharpLabel

現在,在專案根目錄下建立一個名為 SaveService.cs 的新類別文件,並新增以下原始程式碼:

// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF
{
    // SaveService partial class declaration ... this allows a layer of abstraction
    // as we implement the save file details specially for each platform on which this app will
    // operate! 
    public partial class SaveService
    {
        public void SaveAndView(string filename, string contentType, MemoryStream stream)
        {
            SaveFile(filename, contentType, stream);
        }

        // Additional partial files will provide implementations for this method specifically.
        partial void SaveFile(string filename, string contentType, MemoryStream stream);
    }
}
// Change the namespace as desired, but make sure that all source files use this same namespace,
// or there will be errors!
namespace MAUI_IronPDF
{
    // SaveService partial class declaration ... this allows a layer of abstraction
    // as we implement the save file details specially for each platform on which this app will
    // operate! 
    public partial class SaveService
    {
        public void SaveAndView(string filename, string contentType, MemoryStream stream)
        {
            SaveFile(filename, contentType, stream);
        }

        // Additional partial files will provide implementations for this method specifically.
        partial void SaveFile(string filename, string contentType, MemoryStream stream);
    }
}
$vbLabelText   $csharpLabel

由於在使用者裝置上保存內容的實作細節因平台(Windows、Android、macOS 等)而異,因此必須為應用程式將支援的每種裝置類型編寫特定於平台的程式碼。 為了實現這一點,我們將 SaveService 定義為一個部分類別(為了抽象的目的),其中包含一個部分方法,稱為 SaveAndView。 接下來,此方法的實作將在單獨的 SaveService.cs 分部類別中定義,該分部類別適用於解決方案資源管理器中 Platforms 資料夾下的一個或多個資料夾(見下圖):

在.NET MAUI中使用IronPDF建立PDF文件,圖7:實現跨平台的資料夾結構 實作跨平台的資料夾結構

為簡單起見,本教學將僅為 Windows 平台定義上述部分檔案。 在 Windows 平台資料夾下建立一個新的 SaveService.cs 文件,並將以下程式碼新增至該文件:

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

namespace MAUI_IronPDF;

public partial class SaveService
{
    async partial void SaveFile(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();
            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 MAUI_IronPDF;

public partial class SaveService
{
    async partial void SaveFile(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();
            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);
            }
        }
    }
}
$vbLabelText   $csharpLabel

建置並運行 MAUI 應用程式。 將出現一個窗口,其中包含如下所示的介面:

在.NET MAUI中使用IronPDF建立PDF文件,圖8:MAUI應用程式的使用者介面 MAUI應用程式的使用者介面

點擊"生成PDF"按鈕。 片刻之後,將彈出一個窗口,供用戶選擇生成的 PDF 文件的位置。

在.NET MAUI中使用IronPDF建立PDF文件,圖9:選擇儲存PDF文件的位置 選擇儲存 PDF 檔案的位置

結論

IronPDF是最常用的 PDF 轉換庫之一,它允許您產生、讀取、編輯和格式化 PDF 文件。 IronPDF庫提供了許多優點和功能,包括一個瀏覽器引擎,可以幫助將給定的 URL 轉換為 PDF 文件,讓您可以向 HTML 字串添加 CSS 並將其轉換為 PDF 文件,還允許您填寫 PDF 表單。 IronPDF的所有功能都包含在一個資料庫中。

IronPDF提供多種價格方案。 IronPDF的基本價格從 $799 起。 產品支援和更新服務也提供一年期付費服務。 還可以額外購買免版稅再分送保障。

總而言之, IronPDF性能出色,功能豐富,是開發 PDF 文件的理想選擇,值得推薦。 它支援.NET MAUI等通用平台。 它還提供了優秀的幫助和文檔,讓您可以充分利用IronPDF庫的各種功能和功能。

常見問題解答

如何在.NET MAUI應用程式中生成PDF文件?

要在.NET MAUI應用中生成PDF文件,您可以使用IronPDF。首先在Visual Studio中設置一個.NET MAUI專案,通過NuGet安裝IronPDF,並使用ChromePdfRenderer.RenderHtmlAsPdf方法將HTML內容轉換為PDF文檔。

什麼使.NET MAUI適合於跨平台應用程式開發?

.NET MAUI非常適合跨平台應用程式開發,因為它允許開發者使用C#和XAML建立原生行動和桌面應用程式,並支援Android、iOS、macOS和Windows,全部基於單一代碼庫。

IronPDF如何處理PDF轉換中的HTML、CSS和JavaScript?

IronPDF使用Google Chrome引擎準確渲染PDF格式中的HTML、CSS和JavaScript,確保網頁在不丟失格式的情況下轉換。

在.NET MAUI應用中,如何在不同平台上保存PDF文件的過程是什麼?

在使用IronPDF的.NET MAUI應用中,使用SaveService類來保存PDF文件。它包含特定平台的實現來處理Windows和Android等作業系統上的文件保存。

IronPDF在.NET應用程式中有哪些進階功能?

IronPDF 提供諸如創建互動式 PDF、填寫和提交表單、合併和拆分文檔、提取文本和圖像、添加標頭、頁腳和水印等先進功能。

如何在Visual Studio中將IronPDF整合到.NET MAUI專案中?

要將IronPDF整合到.NET MAUI專案中,請在Visual Studio中使用NuGet套件管理器。搜索'IronPDF'並安裝到您的專案中以開始生成和管理PDF。

IronPDF能否在.NET MAUI應用中將網頁網址轉換為PDF?

是的,IronPDF可以透過其網頁渲染功能,準確捕捉HTML、CSS和JavaScript內容並將其渲染成PDF格式。

XAML在設計.NET MAUI應用程式的UI中有什麼作用?

XAML用於.NET MAUI設計應用程式的使用者介面。它允許開發者創建在多個平台上無縫工作的響應式和視覺上吸引人的佈局。

在.NET MAUI專案中使用IronPDF有哪些好處?

IronPDF提供便於使用的特性,廣泛的文件,性能和處理各種PDF任務的能力,使其成為.NET MAUI專案中處理PDF的可靠選擇。

IronPDF是否完全與.NET 10兼容,這帶來了哪些優勢?

是的,IronPDF完全與.NET 10兼容,開箱即用支持版本9、8、7、6、Core、Standard和Framework。使用IronPDF搭配.NET 10可以利用性能提升,例如減少堆積分配,改善JIT/運行時行為和新的C#語言功能,使PDF生成和操作更快、更高效。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

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

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me