在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
.NET MAUI 是下一代 .NET,使开发人员能够使用单一代码库构建跨平台的桌面、Web 和移动应用程序,包括 Xamarin.Forms。 与.NET MAUI现在,您只需编写一次应用程序,就可以使用相同的项目名称将其部署到多个平台,包括 Windows、macOS、iOS、Android 和 tvOS。 .NET MAUI 还能让您利用各个平台上最新的用户界面功能,如 macOS 上的暗模式和触摸支持,或 Windows 10 上的语音识别。
本文将介绍如何在 .NET MAUI 应用程序中使用 IronPDF for .NET 创建 PDF 文档,并带来诸多好处。
IronPDF for .NET 是一个可以生成和编辑 PDF 文件的 .NET 库。 它非常适合在 .NET MAUI 应用程序中使用,因为它提供了广泛的功能,可以根据您的具体需求进行定制。 IronPDF for .NET 具有易于使用的 API,可以轻松地将 PDF 功能集成到您的 .NET MAUI 项目中。
使用 IronPDF 在 .NET MAUI 中创建 PDF 和 PDF 查看器有一些先决条件:
最新版本的 Visual Studio
.NET Framework 6 或 7
Visual Studio 中安装的 MAUI 包
在新项目中安装 IronPdf 的最佳方法之一是使用 Visual Studio 中的 NuGet Package Manager Console。 使用这种方法安装 IronPDF 有一些优势。
首先,通过工具 > NuGet软件包管理器 > 软件包管理器控制台打开软件包管理器控制台。
软件包管理器控制台
接下来,键入以下命令:
Install-Package IronPdf
这将安装软件包及其所有依赖项,如 assets
文件夹。
IronPDF 安装
现在您可以开始在您的 MAUI 项目中使用 IronPDF 了。
首先,为 IronPDF 的三种功能创建一个布局。
对于 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" />
关于 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" />
对于 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" />
.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>
.NET MAUI 没有任何将文件保存到本地存储的预置功能。 因此,有必要自己编写代码。 为创建保存和查看功能,创建了一个名为 "SaveService "的部分类,其中包含一个名为 "SaveAndView "的部分 void 函数,该函数有三个参数:文件名、文件内容类型和用于写入文件的内存流。
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
保存和查看功能需要为每个打算支持以下功能的平台实施(例如,用于安卓、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
对于 Android 和 macOS,您必须创建具有可比的 SaveAndView
实现的单独文件。 您可以从中获得一个工作示例MAUI PDF 查看器 GitHub Repo.
现在,是为 PDF 功能编写代码的时候了。 让我们从 URL 到 PDF 的功能开始。
为 URL 转 PDF 功能创建一个 UrlToPdf
函数。 在函数中,实例化ChromePdfRenderer对象,并使用将URL渲染为PDF将 URL 转换为 PDF 文档的功能。 RenderUrlAsPdf "函数从网络服务器获取 URL 数据并进行处理,将其转换为 PDF 文档。 在参数中,在 URL 输入控件中传递文本,创建一个 SaveService
类对象并使用 SaveAndView
函数。 在 SaveAndView
函数的参数中,传入生成的 PDF 文件流。
保存和查看 "功能有助于将文件保存到任何自定义路径,并提供查看 PDF 文件的选项。 最后,显示一个有关创建 PDF 文件信息的提示框。如果用户尝试使用空输入控件创建 PDF 文件,则会显示一个包含错误信息和警告的提示框。
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");
}
}
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");
}
}
Imports Microsoft.VisualBasic
Private Sub UrlToPdf(ByVal sender As Object, ByVal e As EventArgs)
If URL.Text IsNot Nothing 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
要将 HTML 转换为 PDF 功能,请创建 HtmlToPdf
函数并使用将Html渲染为Pdf功能。 使用编辑器控件的文本,并将其传入 "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
创建用于将 HTML 文件转换为 PDF 文件的 FileToPdf
函数,使用渲染 HTMLFileAsPdf在翻译过程中,您必须使用".NET "函数,并将 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
运行该项目后,输出结果将如下所示。
输出
将 Microsoft 网站 URL 放入此部分,然后单击按钮。
URL 至 PDF
创建 PDF 文件后,会显示一个对话框,要求将文件保存到自定义目的地。
保存文件
保存文件后,该弹出窗口将显示并提供选择 PDF 查看器查看 PDF 文件的选项。
弹出 PDF 查看器
IronPDF 将 URL 出色地转换为 PDF。 译文必须保留所有颜色和图像的原始形状和格式。
弹出 PDF 查看器
所有其他功能也需要遵循同样的程序。 查看以下内容IronPdf in Blazor 博客文章以了解更多有关 IronPdf 在 Blazor 中工作的信息。
了解如何将 MAUI 页面作为 XAML 转换为 PDF 文档,请访问" "。如何在 MAUI 中将 XAML 转换为 PDF".
本教程使用 IronPDF for .NET MAUI 应用程序中的 IronPDF 创建 PDF 文件和 PDF 查看器。 .NET MAUI 是使用单一代码库创建多平台应用程序的绝佳工具。 IronPDF 可帮助在任何 .NET 应用程序中轻松创建和自定义 PDF 文件。 IronPdf 与 .NET MAUI 平台完全兼容。
IronPDF 可免费用于开发。 您可以获得免费试用密钥以在生产中测试 IronPDF。 有关 IronPDF 及其功能的更多信息,请访问IronPDF 官方网站.