Cómo Ver PDF en .NET MAUI (Tutorial Paso a Paso)
.NET MAUI es la próxima generación de .NET que permite a los desarrolladores construir aplicaciones de escritorio, web y móviles multiplataforma, incluyendo Xamarin.Forms, con una sola base de código. Con .NET MAUI, puedes escribir tu aplicación una vez y desplegarla en múltiples plataformas, incluyendo Windows, macOS, iOS, Android y tvOS con el mismo nombre de proyecto. .NET MAUI también te permite aprovechar las últimas capacidades de interfaz de usuario en cada plataforma, como el modo oscuro y el soporte táctil en macOS, o el reconocimiento de voz en Windows 10.
Este artículo explicará cómo usar IronPDF en la aplicación .NET MAUI para crear documentos PDF con muchos beneficios.
Cómo ver archivos PDF en .NET MAUI
- Instalar IronPDF para ver archivos PDF en .NET MAUI
- Configuración del diseño **Frontend** del proyecto MAUI
- Manejar el guardado de archivos en el almacenamiento local y ver PDF
- Utilizar métodos de renderizado para URL, cadena HTML o archivo
- Pasar el PDF renderizado al controlador personalizado en el paso 3
IronPDF: Biblioteca PDF C
IronPDF es una biblioteca .NET que te permite generar y editar archivos PDF. Es perfecto para usar en aplicaciones .NET MAUI, ya que ofrece una amplia gama de características que pueden personalizarse para adaptarse a tus necesidades específicas. Con su API fácil de usar, IronPDF hace que sea sencillo integrar la funcionalidad PDF en tu proyecto .NET MAUI.
Requisitos previos
Existen algunos requisitos previos para crear PDF y visor de PDF en .NET MAUI usando IronPDF:
- La última versión de Visual Studio
- .NET Framework 6 o 7
- Paquetes MAUI instalados en Visual Studio
- Aplicación .NET MAUI funcionando en Visual Studio
Paso 1: Instalar IronPDF
Una de las mejores maneras de instalar IronPDF en un nuevo proyecto es usando la Consola del Administrador de Paquetes de NuGet dentro de Visual Studio. Existen algunas ventajas de usar este método para instalar IronPDF.
- Es fácil de hacer, y
- Puedes estar seguro de que estás usando la última versión de IronPDF.
Pasos para instalar IronPDF
Primero, abre la Consola del Administrador de Paquetes yendo a Herramientas > Administrador de Paquetes NuGet > Consola del Administrador de Paquetes.
Consola del Administrador de Paquetes
A continuación, escribe el siguiente comando:
Install-Package IronPdf
Esto instalará el paquete y todas sus dependencias como la carpeta assets.
Instalación de IronPDF
Ahora puedes comenzar a usar IronPDF en tu proyecto MAUI.
Paso 2: Configurar Diseño Frontend en .NET MAUI
Primero, crea un diseño para las tres funcionalidades de IronPDF.
Diseño de URL a PDF
Para el diseño de URL a PDF, crea una etiqueta con el texto "Ingresar URL para Convertir a PDF" usando un control de etiqueta .NET MAUI. Después de eso, aplica un diseño de pila horizontal para organizar el control de Entrada y el botón horizontalmente. Luego, pon una línea después de los controles para dividir la siguiente sección de controles.
<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" />
Diseño de HTML a PDF
Para el diseño de la sección de HTML a PDF, crea un control Editor y un botón. El control Editor se usará para aceptar una cadena de contenido HTML del usuario. Además, agrega una línea como un divisor.
<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" />
Diseño de archivo HTML a PDF
Para los archivos HTML a PDF, simplemente agrega un botón. Ese botón ayudará a convertir un archivo HTML en un documento PDF usando IronPDF.
<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" />
El código completo de la interfaz de usuario
Se proporciona a continuación el código fuente completo para el frontend de .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>
Paso 3: Código para guardar y ver archivos PDF
.NET MAUI no tiene ninguna función pre-construida para guardar archivos en almacenamiento local. Por lo tanto, es necesario escribir el código nosotros mismos. Para crear la funcionalidad de guardar y ver, se crea una clase parcial denominada SaveService con una función void parcial denominada SaveAndView con tres parámetros: el nombre del archivo, el tipo de contenido del archivo y el flujo de memoria para escribir el archivo.
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
La funcionalidad de guardar y ver necesitará ser implementada para cada plataforma que se quiera soportar (por ejemplo, para Android, macOS y/o Windows). Para la plataforma Windows, cree un archivo llamado "SaveWindows.cs" e implemente el método parcial 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
Para Android y macOS, debes crear archivos separados con implementaciones SaveAndView comparables. Puedes obtener un ejemplo funcional de este Repositorio de GitHub de MAUI PDF Viewer.
Paso 4: Código para las funcionalidades PDF
Ahora, es momento de escribir el código para las funcionalidades PDF. Comencemos con la funcionalidad URL a PDF.
Funcionalidad de URL a PDF
Cree una función UrlToPdf para la funcionalidad de URL a PDF. Dentro de la función, instancia el objeto ChromePdfRenderer y usa la función RenderUrlAsPdf para convertir la URL a documentos PDF. La función RenderUrlAsPdf obtiene los datos de la URL del servidor web y los procesa para convertirlos en un documento PDF. En los parámetros, pase el texto en el control de entrada de URL, cree un objeto de la clase SaveService y utilice la función SaveAndView. En los parámetros de la función SaveAndView, pase el flujo del archivo PDF generado.
La función SaveAndView ayuda a guardar archivos en cualquier ruta personalizada y brinda la opción de ver archivos PDF. Finalmente, muestra un cuadro de alerta con información sobre la creación del archivo PDF. Si un usuario intenta crear un archivo PDF con un control de entrada vacío, mostrará un cuadro de alerta con un mensaje de error y advertencia.
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
Funcionalidad de HTML a PDF
Para convertir la funcionalidad HTML a PDF, cree la función HtmlToPdf y utilice la función RenderHtmlAsPdf . Utilice el texto del control Editor y páselo en los parámetros de la función RenderHtmlAsPdf. De manera similar a la función anterior, utilice la función SaveAndView para habilitar la funcionalidad para ver el archivo PDF después de guardarlo.
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
Funcionalidad de archivo HTML a PDF
Cree la función FileToPdf para convertir archivos HTML en archivos PDF. Utilice la función RenderHtmlFileAsPdf y pase la ruta del archivo HTML como parámetro. Convierte todo el contenido HTML en un PDF y guarda el archivo de salida.
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
Producción
Después de ejecutar el proyecto, la salida se verá así.
Salida
Pon la URL del sitio web de Microsoft en esta sección y haz clic en el botón.
URL a PDF
Después de crear el archivo PDF, muestra un cuadro de diálogo para guardar el archivo en el destino personalizado.
Guardar Archivo
Después de guardar el archivo, aparece este elemento emergente y da la opción de seleccionar un visor de PDF para ver el archivo PDF.
Elemento Emergente de Visor de PDF
IronPDF convierte la URL a PDF de manera sobresaliente. Preserva todos los colores e imágenes en su forma y formato originales.
Elemento Emergente de Visor de PDF
El mismo procedimiento debe seguirse con todas las otras funcionalidades. Consulta esta Entrada de Blog de IronPDF en Blazor para saber más sobre el funcionamiento de IronPDF en Blazor.
Aprende cómo convertir una página MAUI como XAML en un documento PDF visitando "Cómo Convertir XAML a PDF en MAUI".
Resumen
Este tutorial usó IronPDF en la aplicación .NET MAUI para crear un archivo PDF y visor de PDF. El .NET MAUI es una gran herramienta para crear aplicaciones multiplataforma con una sola base de código. IronPDF ayuda a crear y personalizar archivos PDF fácilmente en cualquier aplicación .NET. IronPDF es totalmente compatible con la plataforma .NET MAUI.
IronPDF es gratuito para el desarrollo. Puedes obtener una clave de prueba gratuita para probar IronPDF en producción. Para más información sobre IronPDF y sus capacidades, por favor visita el Sitio Oficial de IronPDF.
Preguntas Frecuentes
¿Cómo puedo integrar un visor de PDF en una aplicación .NET MAUI?
Para integrar un visor de PDF en una aplicación .NET MAUI, puede usar IronPDF para manejar el renderizado y visualización de archivos PDF. IronPDF le permite renderizar PDFs desde URLs, cadenas HTML y archivos HTML, que luego se pueden guardar y mostrar utilizando varias herramientas de visualización de PDF dentro de .NET MAUI.
¿Qué pasos están involucrados en la configuración de IronPDF for .NET MAUI?
Configurar IronPDF for .NET MAUI implica instalar el paquete IronPDF a través del Administrador de Paquetes NuGet en Visual Studio, configurar su proyecto para manejar el renderizado de PDF y usar los métodos de IronPDF para convertir HTML, URLs o archivos HTML en documentos PDF.
¿Cómo puedo asegurarme de que mi diseño de PDF se conserve en .NET MAUI?
IronPDF proporciona capacidades robustas para preservar los diseños de PDF en aplicaciones .NET MAUI. Al usar métodos como RenderHtmlAsPdf o RenderUrlAsPdf, puede convertir su contenido en PDF manteniendo el formato y diseño original.
¿Cuáles son los problemas comunes al ver PDFs en .NET MAUI, y cómo se pueden resolver?
Los problemas comunes al ver PDFs en .NET MAUI incluyen errores de renderizado específicos de la plataforma y permisos de acceso a archivos. Estos se pueden resolver utilizando las capacidades multiplataforma de IronPDF y asegurando un manejo adecuado de los permisos de archivos en la base de código de su aplicación.
¿Puedo convertir contenido HTML a PDF en una aplicación .NET MAUI?
Sí, puede convertir contenido HTML en PDF en una aplicación .NET MAUI usando el método RenderHtmlAsPdf de IronPDF. Esto le permite transformar cadenas HTML en documentos PDF completamente formateados de manera eficiente.
¿Cómo manejo el guardado y visualización de archivos en .NET MAUI?
En .NET MAUI, puede usar IronPDF para generar archivos PDF y luego implementar el guardado y visualización de archivos usando APIs de manejo de archivos específicas de la plataforma. IronPDF soporta guardar archivos PDF en el almacenamiento local, que luego se pueden abrir con un visor de PDF.
¿Es IronPDF compatible con todas las plataformas objetivo de .NET MAUI?
Sí, IronPDF es compatible con todas las plataformas objetivo de .NET MAUI, incluidas Windows, macOS, iOS, Android y tvOS, proporcionando una experiencia fluida de creación y visualización de PDFs en estos sistemas.
¿Cómo puedo probar IronPDF en mi proyecto .NET MAUI antes del despliegue completo?
Puede probar IronPDF en su proyecto .NET MAUI usando su licencia de desarrollo gratuita. Esto le permite integrar y probar funcionalidades de PDF en su aplicación antes de comprometerse con una licencia de producción completa.
¿IronPDF es compatible con .NET 10 y qué beneficios aporta?
Sí, IronPDF es totalmente compatible con .NET 10. Funciona de inmediato, sin necesidad de soluciones alternativas personalizadas, al crear aplicaciones con .NET 10, incluyendo MAUI, aplicaciones web, de escritorio y en la nube. Usar .NET 10 le da acceso a las últimas mejoras de la plataforma, mejoras de rendimiento y API actualizadas.


