如何在.NET MAUI中查看PDF(逐步教程)
.NET MAUI 是下一代 .NET,它使開發人員能夠使用單一程式碼庫建立跨平台的桌面、Web 和行動應用程式,包括 Xamarin.Forms。 使用.NET MAUI ,您可以編寫一次應用程式,並使用相同的專案名稱將其部署到多個平台,包括 Windows、macOS、iOS、Android 和 tvOS。 .NET MAUI 還使您能夠利用每個平台上的最新 UI 功能,例如 macOS 上的深色模式和觸控支援,或 Windows 10 上的語音識別。
本文將介紹如何在 .NET MAUI 應用程式中使用 IronPDF 建立 PDF 文檔,並介紹其許多優勢。
如何在 .NET MAUI 中查看 PDF 文件
- 安裝 IronPDF 以在 .NET MAUI 中查看 PDF 文件
- MAUI專案的前端設計搭建
- 在本地儲存中處理檔案儲存和 PDF 檢視
- 使用 URL、HTML 字串或檔案的渲染方法
- 將渲染的 PDF 傳遞給步驟 3 的自定義處理器
IronPDF:C# PDF 函式庫
IronPDF 是一個 .NET 函式庫,可用於產生和編輯 PDF 檔案。 它非常適合在 .NET MAUI 應用程式中使用,因為它提供了一系列可自訂的功能,以滿足您的特定需求。 IronPDF 擁有易於使用的 API,可輕鬆地將 PDF 功能整合到您的 .NET MAUI 專案中。
先決條件
使用 IronPDF 在 .NET MAUI 中建立 PDF 和 PDF 檢視器有一些先決條件:
- 最新版本的 Visual Studio
- .NET Framework 6 或 7
- Visual Studio 中已安裝 MAUI 套件
- 在 Visual Studio 中執行的 .NET MAUI 應用程式
步驟 1:安裝 IronPDF
在新專案中安裝 IronPDF 的最佳方法之一是使用 Visual Studio 中的 NuGet 套件管理器控制台。 使用這種方法安裝 IronPDF 有一些優點。
- 這很容易做到,而且 您可以放心,您使用的是最新版本的 IronPDF。
安裝 IronPDF 的步驟
首先,透過前往"工具" > "NuGet 套件管理員" > "套件管理員控制台"來開啟套件管理員控制台。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 1:套件管理器控制台 軟體包管理器控制台
接下來,輸入以下命令:
Install-Package IronPdf
這將安裝該軟體包及其所有依賴項,例如 assets 資料夾。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 2:IronPDF 安裝 IronPDF 安裝
現在您可以在 MAUI 專案中開始使用 IronPDF 了。
步驟 2:在 .NET MAUI 中設定前端設計
首先,為 IronPDF 的三個功能建立一個佈局。
PDF佈局的URL
對於 URL 到 PDF 的佈局,使用 .NET MAUI 標籤控制項建立一個帶有文字"輸入要轉換 PDF 的 URL"的標籤。 之後,套用水平堆疊佈局,將輸入控制和按鈕水平排列。 然後在控制項後面加一條線,將下一部分控制項分隔開來。
<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 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 轉 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" />
<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 版面
將 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" />
<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" />
完整的 UI 程式碼
下面給出了 .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>
<?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>
步驟 3:編寫儲存和檢視 PDF 檔案的程式碼
.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功能程式碼
現在,是時候編寫 PDF 功能的程式碼了。 我們先從URL轉PDF功能開始。
URL 轉 PDF 功能
為 URL 轉 PDF 功能建立一個 UrlToPdf 函數。 在函數內部,實例化ChromePdfRenderer對象,並使用RenderUrlAsPdf函數將 URL 轉換為 PDF 文件。 RenderUrlAsPdf 函數從 Web 伺服器取得 URL 數據,並對其進行處理以將其轉換為 PDF 文件。 在參數中,傳遞 URL 輸入控制項中的文本,建立一個 SaveService 類別的對象,並使用 SaveAndView 函數。 在 SaveAndView 函數的參數中,傳入產生的 PDF 檔案流。
SaveAndView 功能可協助將檔案儲存至任何自訂路徑,並提供檢視 PDF 檔案的選項。 最後,顯示一個提示框,其中包含有關建立 PDF 文件的資訊。如果使用者嘗試使用空的輸入控制項建立 PDF 文件,則會顯示包含錯誤訊息和警告的提示方塊。
private void UrlToPdf(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(URL.Text))
{
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 (!string.IsNullOrEmpty(URL.Text))
{
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 Not String.IsNullOrEmpty(URL.Text) 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功能
若要實現 HTML 到 PDF 的轉換功能,請建立 HtmlToPdf 函數並使用RenderHtmlAsPdf函數。 使用編輯器控制項的文本,並將其作為 RenderHtmlAsPdf 函數的參數傳遞。 與上述功能類似,使用 SaveAndView 功能可以啟用儲存後檢視 PDF 檔案的功能。
private void HtmlToPdf(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(HTML.Text))
{
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 (!string.IsNullOrEmpty(HTML.Text))
{
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 Not String.IsNullOrEmpty(HTML.Text) 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 函數,用於將 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
輸出
專案運行後,輸出結果將如下所示。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 3:輸出 輸出
在此輸入微軟網站網址,然後按一下按鈕。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 4:PDF 的 URL PDF檔案的URL
建立 PDF 檔案後,會顯示一個對話框,讓使用者將文件儲存到自訂目標位置。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 5:儲存文件 儲存檔案
儲存文件後,會彈出此窗口,並提供選擇 PDF 檢視器以查看 PDF 文件的選項。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 6:PDF 檢視器彈出窗口 PDF檢視器彈出視窗
IronPDF 將 URL 轉換為 PDF 的效果非常出色。 它保留了所有顏色和圖像的原始形狀和格式。
如何在 .NET MAUI 中查看 PDF(逐步教學),圖 7:PDF 檢視器彈出窗口 PDF檢視器彈出視窗
其他所有功能都需要遵循相同的步驟。 請查看這篇IronPDF 在 Blazor 的部落格文章,以了解更多關於 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 官方網站。
常見問題解答
如何在 .NET MAUI 應用中整合 PDF 檢視器?
要在 .NET MAUI 應用中整合 PDF 檢視器,您可以使用 IronPDF 來處理 PDF 檔案的渲染和檢視。IronPDF 可讓您從 URL、HTML 字串和 HTML 檔案渲染 PDF,然後使用 .NET MAUI 內的各種 PDF 檢視器工具儲存並顯示。
設置 IronPDF 以供 .NET MAUI 使用的步驟有哪些?
為 .NET MAUI 設置 IronPDF 包括通過 Visual Studio 的 NuGet 套件管理器安裝 IronPDF 套件,配置專案以處理 PDF 渲染,並使用 IronPDF 的方法將 HTML、URL 或 HTML 檔案轉換為 PDF 文件。
如何確保我的 PDF 佈局在 .NET MAUI 中得以保留?
IronPDF 在 .NET MAUI 應用中提供了強大的保持 PDF 佈局的能力。通過使用 RenderHtmlAsPdf 或 RenderUrlAsPdf 這樣的方法,您可以在將內容轉換為 PDF 時保留原始格式和佈局。
在 .NET MAUI 中檢視 PDF 時常見的問題是什麼,以及如何解決?
在 .NET MAUI 中檢視 PDF 時常見的問題包括平台特定的渲染錯誤和檔案訪問權限。這些問題可以通過使用 IronPDF 的跨平台能力和在應用程式代碼庫中正確處理檔案權限來解決。
我可以在 .NET MAUI 應用中將 HTML 內容轉換為 PDF 嗎?
是的,您可以使用 IronPDF 的 RenderHtmlAsPdf 方法在 .NET MAUI 應用中將 HTML 內容轉換為 PDF。這使您能夠有效地將 HTML 字串轉換為完整格式的 PDF 文檔。
如何在 .NET MAUI 中處理檔案儲存和檢視?
在 .NET MAUI 中,您可以使用 IronPDF 生成 PDF 檔,然後通過平台特定的檔案處理 API 實現檔案儲存和檢視。IronPDF 支援將 PDF 檔案儲存到本地存儲中,然後可以用 PDF 檢視器開啟。
IronPDF 是否與 .NET MAUI 的所有目標平台兼容?
是的,IronPDF 與 .NET MAUI 的所有目標平台兼容,包括 Windows、macOS、iOS、Android 和 tvOS,提供在這些系統上流暢的 PDF 創建和檢視體驗。
我可以如何在全面部署之前在我的 .NET MAUI 專案中測試 IronPDF?
您可以使用其免費開發許可證在您的 .NET MAUI 專案中測試 IronPDF。這允許您在承諾正式生產許可證之前整合和測試應用中的 PDF 功能。
IronPDF是否支持.NET 10,這帶來了哪些好處?
是的,IronPDF完全支持.NET 10。無需任何自定義解決方案即可在使用.NET 10構建應用程式時正常運行,包括MAUI、網頁、桌面和基於雲的應用。使用.NET 10可讓您訪問最新的平臺改進、性能增強和更新的API。



