使用IRONPDF

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

更新 2024年二月11日
分享:

简介

.NET多平台应用程序用户界面 (.NET MAUI) .NET MAUI 是一个跨平台框架,用于使用 C# 和 XAML 创建本地移动和桌面应用程序。您可以使用 .NET MAUI 在 Android、iOS、MacOS 和 Windows 上使用单一代码库进行操作。.NET MAUI 是开源的,是对 Xamarin Forms 的改进。为了提高性能和可扩展性,从头开始重新编写了用户界面控件。此外,它还从移动平台扩展到桌面用例。如果您曾经使用过 Xamarin Forms 来创建跨平台用户界面,那么您会发现 .NET MAUI 框架与它有很多共同之处。

不过,两者也有一些不同之处。您可以使用 .NET MAUI 框架的单个项目构建多平台应用程序,但如果需要,您可以添加特定平台的代码和资源。.NET MAUI 的主要目标之一是让您在单一代码库中编写尽可能多的应用程序逻辑和用户界面布局。.NET MAUI 将适用于所有平台,并支持现有的 MVVM 和 XAML 模式。

.NET MAUI 允许开发人员在各种平台上工作,如移动开发和 Windows 平台。

IronPDF 功能

IronPDF 是一款功能强大的 PDF 转换器,几乎可以处理浏览器可以处理的任何任务。面向开发人员的 .NET 库使 PDF 文件的创建、读取和处理变得简单。IronPDF 使用 Google Chrome 引擎将 HTML 转换为 PDF 文件。除其他网络技术外,IronPDF 还支持 HTML、ASPX.NET 和 .NET 技术、 剃刀页和 MVC 视图。IronPDF 支持 Microsoft .NET 应用程序 (ASP.NET 网络应用程序和传统 Windows 应用程序).IronPDF 还可用于制作精美的 PDF 文档。

IronPDF 可以 从 HTML 文件创建 PDF 文件 包含 JavaScript、CSS 和图像文件。

不仅可以 将 HTML 文件转换为 PDF但也可以 将图像文件转换为 PDF.

IronPDF 可帮助创建交互式 PDF 文档、 填写和提交互动表格, 合并和拆分 PDF 文档, 提取文本和图像 从 PDF 文档中搜索 PDF 文档中的文本,将 PDF 页面光栅化为图像,将 PDF 转换为 HTML,以及 打印 PDF 文档.

IronPDF 可以从 URL 生成文档。用于在 HTML 后面登录 登录表格此外,它还允许使用自定义网络登录凭证、用户代理、代理、cookies、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 文档并将其保存到合适的位置。

使用 IronPDF 在 .NET MAUI 中创建 PDF 文件,图 1:在 Visual Studio 中创建新项目

在 Visual Studio 中创建一个新项目

在相应的文本框中输入项目名称并选择文件路径。然后,单击创建按钮,如下图所示。

使用 IronPDF 在 .NET MAUI 中创建 PDF 文件,图 2:配置项目

配置项目

Visual Studio 项目现在将按照 .NET MAUI 应用程序平台为所选应用程序生成结构,它现在将打开 MainPage.cs 文件以添加代码并构建/运行应用程序。

使用 IronPDF 在 .NET MAUI 中创建 PDF 文件,图 3:在 MainPage.cs 文件中添加代码

在 MainPage.cs 文件中添加代码

接下来,安装库以测试代码。

安装 IronPDF 库

IronPDF 库可以通过四种方式下载和安装。

它们是

  • 使用 Visual Studio。
  • 使用 Visual Studio 命令行
  • 从 NuGet 网站直接下载。
  • 从 IronPDF 网站直接下载。

使用 Visual Studio

Visual Studio 软件提供了 NuGet 包管理器选项,可直接将软件包安装到解决方案中。下面的截图显示了如何打开 NuGet 包管理器。

使用 IronPDF 在 .NET MAUI 中创建 PDF 文件,图 4:导航至 NuGet 包管理器用户界面

导航至 NuGet 软件包管理器用户界面

这提供了一个搜索框,用于显示 NuGet 网站上的软件包列表。在 NuGet 软件包管理器中,搜索关键字 "IronPDF",如下图所示。

在 .NET MAUI 中使用 IronPDF 创建 PDF 文件,图 5:从 NuGet 软件包管理器用户界面选择 IronPdf 软件包

从 NuGet 软件包管理器用户界面下载 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 应用程序用户界面的地方。

请按照下面的代码操作。

<?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 "方法会生成一个新的 PDF 文档,其中包含文本 "Hello, IronPDF!......",并将其保存到用户电脑的指定位置。

在上述方法中,一个新的 ChromePdfRenderer 对象,并调用 将Html渲染为Pdf 方法生成一个新的 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);
    }
}
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#

由于在用户设备上保存内容的实施细节因平台而异 (视窗、安卓、MacOS 等)因此,有必要为应用程序将支持的每种设备类型编写特定于平台的代码。为此,我们将 SaveService 定义为一个局部类 (为便于抽象) 包含一个部分方法,名为 SaveAndView。之后,该方法的实现将在单独的 SaveService.cs 部分类中定义,用于解决方案资源管理器中 Platforms 文件夹嵌套的一个或多个文件夹。 (见下图):

使用 IronPDF 在 .NET MAUI 中创建 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 应用程序的用户界面

点击 "生成 PDF "按钮。片刻后,弹出窗口让您选择生成 PDF 文件的位置。

使用 IronPDF 在 .NET MAUI 中创建 PDF 文件,图 9:选择保存 PDF 文件的位置

选择保存 PDF 文件的位置

结论

IronPDF 是最常用的 PDF 转换库之一,它允许你生成、阅读、编辑和格式化 PDF。IronPDF 库提供了许多优点和功能,其中包括一个浏览器引擎,可帮助将给定的 URL 转换为 PDF 文件,允许您为 HTML 字符串添加 CSS 并将其转换为 PDF 文件,还允许您填写 PDF 表单。IronPDF 的所有功能都包含在一个库中。

IronPDF 有多种价格结构。IronPDF 的基本价格为 $749。产品支持和更新的费用为一年。免版税的再分发范围也可作为附加项目购买。

总之,我们推荐使用 IronPDF,因为它能为处理 PDF 的开发人员提供出色的性能和大量功能。它支持 .NET MAUI 等通用平台。此外,它还提供了出色的帮助和文档,让您可以充分利用 IronPDF 库的广泛功能及其众多特性。

< 前一页
使用Blazor教程创建PDF文件
下一步 >
如何在C#中将图像转换为PDF [代码示例教程]

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >