在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
.NET MAUI 是 .NET 的下一代技術,讓開發人員能夠使用單一代碼庫構建跨平台的桌面、Web 和移動應用程式,包括 Xamarin.Forms。 與.NET MAUI,您可以編寫一次應用程式,然後在多個平台上部署,包括 Windows、macOS、iOS、Android 和 tvOS,且使用相同的專案名稱。 .NET MAUI 也使您能在各平台上利用最新的 UI 功能,例如 macOS 的深色模式和觸控支援,或 Windows 10 的語音識別。
本文將說明如何在 .NET MAUI 應用程式中使用 IronPDF 來創建具有許多優點的 PDF 文件。
IronPDF是一個.NET庫,使您可以生成和編輯PDF文件。 它非常適合用於 .NET MAUI 應用程式,因為它提供了一系列廣泛的功能,可以根據您的具體需求進行自定義。 IronPDF 的易於使用的 API,使您可以輕鬆地將 PDF 功能整合到您的 .NET MAUI 專案中。
在使用IronPDF於.NET MAUI中創建PDF和PDF Viewer之前,有一些先決條件:
Visual Studio 的最新版本
.NET Framework 6 或 7
在 Visual Studio 中安裝的 MAUI 套件
在 Visual Studio 中使用 NuGet 封裝管理員主控台是將 IronPDF 安裝到新項目的最佳方式之一。 使用此方法安裝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
需要為每個打算支持的平台實現保存和查看功能(例如,適用於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
對於 Android 和 macOS,您需要創建具有可比 SaveAndView
實現的單獨文件。 您可以從這裡獲得一個有效的範例MAUI PDF Viewer GitHub 存储库.
現在,是時候編寫 PDF 功能的程式碼了。 讓我們從 URL 轉換為 PDF 功能開始。
創建一個 UrlToPdf
函式來實現 URL 到 PDF 的功能。 在函數內,實例化ChromePdfRenderer
物件並使用RenderUrlAsPdf
將 URL 轉換為 PDF 文件的函式。 RenderUrlAsPdf
函數從網頁伺服器獲取 URL 的數據,並處理以將其轉換為 PDF 文件。 在參數中,傳遞 URL 輸入控制中的文字,建立一個 SaveService
類別的物件,並使用 SaveAndView
函數。 在 SaveAndView
函數的參數中,傳入生成的 PDF 文件的流。
SaveAndView
函數有助於將文件保存到任何自訂路徑,並提供查看 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
函數並使用RenderHtmlAsPdf
函數。 使用 Editor 控制的文本,並將其作為參數傳入 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
創建 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
執行專案後,輸出將如下所示。
輸出
將 Microsoft 網站的 URL 放在此區域並點擊按鈕。
URL 轉 PDF
在創建 PDF 文件後,會顯示一個對話框以在自定位置保存文件。
儲存檔案
儲存檔案後,此彈出視窗顯示並提供選擇 PDF 檢視器以查看 PDF 檔案的選項。
PDF 檢視器彈出視窗
IronPDF 出色地將 URL 轉換為 PDF。 它保留所有顏色和圖像的原始形狀和格式。
PDF 檢視器彈出視窗
同樣的程序需要應用於所有其他功能。 查看這個Blazor 中的 IronPDF 部落格文章了解有關 IronPDF 在 Blazor 中運作的更多資訊。
了解如何將 MAUI 頁面作為 XAML 轉換為 PDF 文件,請造訪 "如何在MAUI中將XAML轉換成PDF"."
本教程在 .NET MAUI 應用程式中使用 IronPDF 來創建 PDF 檔案和 PDF 檢視器。 .NET MAUI 是一個非常好的工具,可以用單一的代碼基礎來創建多平台應用程式。 IronPDF可在任何.NET應用程式中輕鬆創建和自訂PDF文件。 IronPDF 與 .NET MAUI 平台完全相容。
IronPDF 在開發中是免費的。 您可以獲得一個免費試用密鑰在生產環境中測試IronPDF。 如需有關 IronPDF 及其功能的更多資訊,請訪問IronPDF 官方網站.