使用 IRONPDF

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

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

介紹

.NET 多平台應用程序 UI (.NET MAUI) 是一個跨平台框架,用於使用 C# 和 XAML 創建原生行動和桌面應用程序。你可以使用 .NET MAUI 在 Android、iOS、MacOS 和 Windows 上運行,同時只需一個代碼庫。 .NET MAUI 是開源的,是 Xamarin Forms 的改進版。UI 控件從根本上重新編寫,提升了性能和可擴展性。此外,它還從行動平台擴展到包含桌面使用案例。如果你曾經使用 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 還支持 HTML、ASPX。 Razor Pages,和 MVC 視圖。IronPDF 支援 Microsoft .NET 應用程式 (ASP.NET Web 應用程式和傳統 Windows 應用程式). IronPDF 也可以用來製作吸引人的 PDF 文件。

IronPDF 可以 從 HTML 檔案創建 PDF 檔案 包含 JavaScript、CSS 和圖像檔案。

不僅僅是 HTML 檔案轉換為 PDF,但也可以 將圖像文件轉換為PDFIronPDF 可以幫助創建互動式 PDF 文件。 填寫並提交互動表單, 合併和分割 PDF 文件, 提取文字和圖片 從 PDF 文件中提取文字、在 PDF 文件中搜尋文字、將 PDF 頁面光柵化為圖像、將 PDF 轉換為 HTML,並 列印 PDF 文件.

IronPDF可以從URL生成文件。對於HTML後的登錄 登入表單,它還允許使用自訂的網路登入憑證、用戶代理、代理伺服器、Cookie、HTTP 標頭和表單變數。

IronPDF是一個可以讀取和填寫PDF文件的庫,並且能夠從文件中提取圖像。它允許我們 添加頁眉,頁腳文字,照片, 書籤添加浮水印等內容到文件。它也允許我們在新文件或現有文件中合併和拆分頁面。IronPDF 能夠在不使用 Acrobat 檢視器的情況下將文檔轉換成 PDF 物件。還可以將 CSS 文件轉換為 PDF 文件,CSS 媒體類型文件也可以轉換成文檔。

在 Visual Studio 中創建新專案

首先,使用 Visual Studio Code 和 Visual Studio 創建專案。在使用 Visual Studio Code 時,需要使用命令行工具來安裝專案類型範本。

打開 Microsoft Visual Studio 軟體,進入文件菜單,選擇「新專案」,在新專案窗口中選擇「.NET MAUI App」。本文將使用 .NET MAUI App 來生成 PDF 文件並將其保存到合適的位置。

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

在 Visual Studio 中創建一個新項目

在相應的文字框中輸入項目名稱並選擇文件路徑。然後,如下圖所示,點擊 Create 按鈕。

使用 IronPDF 在 .NET MAUI 中創建 PDF 文件,圖 2:配置項目

配置專案

Visual Studio 專案現在會按照 .NET MAUI App 平台生成所選應用程式的結構,接下來它會開啟 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 套件管理器。

NuGet Package Manager

在 .NET MAUI 中使用 IronPDF 創建 PDF 文件,圖 4: 前往 NuGet 套件管理器 UI

導航至NuGet套件管理器UI

這裡提供搜尋框來顯示NuGet網站上的套件列表。在NuGet套件管理器中,搜尋關鍵字「IronPDF」,如下面的截圖所示。

在 .NET MAUI 中使用 IronPDF 創建 PDF 文件,圖 5:從 NuGet 套件管理器 UI 中選擇 IronPdf 套件

從 NuGet Package Manager UI 中的 IronPdf 套件

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

使用 Visual Studio 命令行

在 Visual Studio 中,依次点击 工具 > NuGet 套件管理器 > 套件管理器控制台

在套件管理器控制台标签页中输入以下行:

Install-Package IronPdf

現在,該套件將下載/安裝到當前專案的所有 .NET MAUI 平台並準備使用。

在.NET MAUI中使用IronPDF創建PDF文件,圖6:在程序包管理控制台中安裝程序包

在套件管理主控台中安裝套件

從NuGet網站直接下載

第三種方式是通過訪問NuGet網站,直接下載NuGet套件 IronPdf 套件連結 前往 NuGet IronPDF 存儲庫頁面。

  • 從右邊的菜單中選擇下載包選項。
  • 雙擊下載的包。它將自動安裝。
  • 重新載入解決方案,該包應該可以在你的項目中使用。

從 IronPDF 網站直接下載

點擊 下載最新壓縮檔案的連結 直接從網站下載。下載後,按照以下步驟將套件添加到您的項目中。

  • 右鍵點擊解決方案窗口中項目的 Dependencies 選項。
  • 選擇具體的平台,然後選擇參考選項並瀏覽下載的參考位置。
  • 點擊確定以添加參考。

您還需要添加所有支援 .NET MAUI 平台的參考。

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

當專案建立後,會有一個自動產生的檔案,名稱為 MainPage.xaml。這是放 .NET MAUI 應用程式 UI 的地方。

請遵循以下程式碼。

<?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);
}
Private Sub GeneratePDF(ByVal sender As Object, ByVal e As EventArgs)
	Dim renderer As New ChromePdfRenderer()
	Dim doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>")

	'Saves the memory stream as file.
	Dim saveService As New SaveService()
	saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream)
End Sub
VB   C#

GeneratePDF 方法生成一個包含文字 "Hello, IronPDF" 的新 PDF 文件!並將其保存在用戶計算機上的指定位置。

在上述方法中,一個新的 ChromePdfRenderer 物件已創建並調用 RenderHtmlAsPdf 生成包含“Hello IronPDF”字樣的新 PDF 文件的方法! 從一串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);
    }
}
Imports IronPdf

' 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

	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub GeneratePDF(ByVal sender As Object, ByVal e As EventArgs)
			Dim renderer As New ChromePdfRenderer()
			Dim doc = renderer.RenderHtmlAsPdf("<h1>Hello IronPDF!</h1> <p>I'm using IronPDF MAUI!</p>")
			'Saves the memory stream as file.
			Dim saveService As New SaveService()
			saveService.SaveAndView("IronPDF HTML string.pdf", "application/pdf", doc.Stream)
		End Sub
	End Class
End Namespace
VB   C#

現在,在專案的根目錄中創建一個新的類文件,命名為 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);
    }
}
' 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! 
	Partial Public Class SaveService
		Public Sub SaveAndView(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
			SaveFile(filename, contentType, stream)
		End Sub

		' Additional partial files will provide implementations for this method specifically.
		Partial Private Sub SaveFile(ByVal filename As String, ByVal contentType As String, ByVal stream As MemoryStream)
		End Sub
	End Class
End Namespace
VB   C#

由於每個平台在儲存內容到用戶設備上的實作細節各不相同 (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);
            }
        }
    }
}
Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.Storage.Streams
Imports Windows.UI.Popups

Namespace MAUI_IronPDF

	Partial Public Class SaveService
		Private Async Sub SaveFile(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#

構建並運行 MAUI 應用程式。將出現一個包含如下界面的窗口:

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

MAUI App 的用戶介面

點擊「生成 PDF」按鈕。幾秒鐘後,將會彈出選擇生成的 PDF 文件位置的彈窗。

在 .NET MAUI 中使用 IronPDF 創建 PDF 文件,圖 9:選擇保存 PDF 文件的位置

選擇保存 PDF 檔案的位置

結論

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

IronPDF 提供了各種定價結構。IronPDF 的基本價格從 $749 起。產品支持和更新也可按年費提供。無版稅的重新分發覆蓋也可以作為附加項購買。

總結來說,IronPDF 因其優異的性能和大量功能而受到推薦,非常適合處理 PDF 的開發人員。它支持跨平台如 .NET MAUI,還提供了出色的支持和文件,讓您可以充分利用 IronPDF 庫及其眾多功能。

< 上一頁
使用 Blazor 教程創建 PDF 文件
下一個 >
如何在C#中將圖片轉換為PDF【代碼示例教學】

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

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