Cómo ver PDFs en .NET con IronPDF C
IronPDF muestra PDFs en aplicaciones .NET a través del control IronPdf.Viewer.Maui para MAUI, rasterizando páginas a imágenes con RasterizeToImageFiles para cualquier marco de UI, y a través de controles host como WebView2 en WPF y Windows Forms. La elección correcta depende del tipo de aplicación que estés construyendo y cuánto chrome de visualización necesites.
"Ver" significa diferentes cosas en estos caminos. El visor MAUI es un componente interactivo completo con una barra de herramientas. El camino de rasterización convierte cada página en una imagen que puedes mostrar en cualquier control. Las rutas de WebView2 y del visor por defecto entregan el archivo a un motor de navegador o al lector PDF instalado por el usuario. Este artículo muestra cada uno y es honesto sobre lo que hace y no te ofrece.
Inicio rápido: Ver un PDF en MAUI con IronPDF
Agrega el paquete NuGet IronPdf.Viewer.Maui, llama a ConfigureIronPdfView() en MauiProgram.cs, luego vincula un PDF a un IronPdfView. La línea única a continuación carga un archivo en el control de visualización.
-
Instala IronPDF con el Administrador de Paquetes NuGet
-
Copie y ejecute este fragmento de código.
new IronPdf.Viewer.Maui.IronPdfView { Source = IronPdf.Viewer.Maui.IronPdfViewSource.FromFile("document.pdf") }; -
Despliegue para probar en su entorno real
Comienza a usar IronPDF en tu proyecto hoy mismo con una prueba gratuita
Instala el paquete primero con Install-Package IronPdf.Viewer.Maui, y añade tu clave de licencia de IronPDF en ConfigureIronPdfView para eliminar la marca de prueba. El tutorial del visor MAUI guía a través de la configuración completa del proyecto.
Flujo de trabajo mínimo (5 pasos)
- Install IronPDF from NuGet for .NET PDF rendering
- Elige una ruta de visualización: visor MAUI, rasterizar a imagen, WebView2, o el visor del sistema por defecto
- Inserta un PDF en ASP.NET con un
iframeHTML - Renderiza páginas de PDF a imágenes para visualización en WPF, WinForms o Blazor
- Abre un PDF en el lector instalado del usuario con
System.Diagnostics.Process.Start
¿Cómo veo PDFs en ASP.NET y MVC?
Sirve el PDF desde una acción de controlador e incrústalo con un HTML iframe. El visor de PDF integrado del navegador maneja la renderización, por lo que el documento aparece en línea mientras tu diseño de página permanece intacto. Cuando el PDF se genera al vuelo, la conversión de HTML a PDF de IronPDF produce el archivo que la acción devuelve.
// Controller action to serve PDF
public ActionResult ViewPdf()
{
var pdfPath = Server.MapPath("~/Content/sample.pdf");
return File(pdfPath, "application/pdf");
}
// In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
// Controller action to serve PDF
public ActionResult ViewPdf()
{
var pdfPath = Server.MapPath("~/Content/sample.pdf");
return File(pdfPath, "application/pdf");
}
// In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
Imports System.Web.Mvc
' Controller action to serve PDF
Public Function ViewPdf() As ActionResult
Dim pdfPath = Server.MapPath("~/Content/sample.pdf")
Return File(pdfPath, "application/pdf")
End Function
' In your Razor view
<iframe src="@Url.Action("ViewPdf")" width="100%" height="600px"></iframe>
Si necesitas selección de texto, zoom y navegación por páginas que controlas en lugar de la configuración por defecto del navegador, renderiza las páginas del PDF a imágenes (mostrado abajo) y muéstralas, o conecta un visor JavaScript de tu elección.
¿Cómo muestro páginas de PDF como imágenes en WPF, WinForms o Blazor?
Llama a RasterizeToImageFiles para convertir cada página del PDF en un PNG, luego muestra esas imágenes en cualquier control: un Image de WPF, un PictureBox de WinForms, o un <img> en un componente Blazor. Esta es la ruta de visualización nativa de IronPDF. Funciona igual en cada marco de UI y en cada sistema operativo que IronPDF soporta, porque produce archivos de imagen simples en lugar de depender de un control de navegador host.
Entrada
:path=/static-assets/pdf/content-code-examples/how-to/net-pdf-viewer-rasterize.cs
using IronPdf;
// Load the PDF you want to display.
PdfDocument pdf = PdfDocument.FromFile("sample-report.pdf");
// Render every page to a PNG. The asterisk in the path is replaced with the page number,
// producing viewer-page-1.png, viewer-page-2.png, and so on. The last argument (100) is the DPI.
pdf.RasterizeToImageFiles("viewer-page-*.png", IronPdf.Imaging.ImageType.Png, 100);
// To show a page inside a GUI control without writing to disk, get in-memory bitmaps instead.
// ToBitmap returns one AnyBitmap per page; bind bitmaps[0] to a WPF Image or a WinForms PictureBox.
var bitmaps = pdf.ToBitmap();
bitmaps[0].SaveAs("viewer-firstpage.png");
Imports IronPdf
' Load the PDF you want to display.
Dim pdf As PdfDocument = PdfDocument.FromFile("sample-report.pdf")
' Render every page to a PNG. The asterisk in the path is replaced with the page number,
' producing viewer-page-1.png, viewer-page-2.png, and so on. The last argument (100) is the DPI.
pdf.RasterizeToImageFiles("viewer-page-*.png", IronPdf.Imaging.ImageType.Png, 100)
' To show a page inside a GUI control without writing to disk, get in-memory bitmaps instead.
' ToBitmap returns one AnyBitmap per page; bind bitmaps(0) to a WPF Image or a WinForms PictureBox.
Dim bitmaps = pdf.ToBitmap()
bitmaps(0).SaveAs("viewer-firstpage.png")
Salida
Para una opción en memoria, ToBitmap devuelve una imagen por página que puedes vincular a un control sin tocar el disco. Ajusta el argumento DPI para intercambiar el tamaño del archivo contra la nitidez, el mismo control que tienes sobre las opciones de renderización de IronPDF al producir el documento.
¿Cómo veo PDFs en aplicaciones WPF?
Hospeda el PDF en un control WebView2, el cual usa el motor Chromium de Microsoft Edge y lleva su propio visor de PDF (incluyendo barra de herramientas, zoom e impresión). Guarda el documento en disco, luego navega el control al URI del archivo. WebView2 es el reemplazo actual para el control WebBrowser más antiguo, que dependía del motor Internet Explorer obsoleto.
:path=/static-assets/pdf/content-code-examples/how-to/net-pdf-viewer-wpf-viewer.cs
// WPF: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2 and add a <wv2:WebView2 x:Name="pdfWebView" />
// element to your XAML (xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf").
// WebView2 renders PDFs with the same built-in viewer as the Edge browser (toolbar, zoom, print).
using System;
using System.IO;
// Save the IronPDF-generated document to disk first, then point WebView2 at it.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control declared in your XAML.
// EnsureCoreWebView2Async must complete before navigating.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the older System.Windows.Controls.WebBrowser control still works on
// Windows machines that have a PDF handler installed, but it relies on the deprecated Internet
// Explorer engine and is not recommended for new applications. Prefer WebView2 above.
Imports System
Imports System.IO
Imports IronPdf
' WPF: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
' Install the NuGet package Microsoft.Web.WebView2 and add a <wv2:WebView2 x:Name="pdfWebView" />
' element to your XAML (xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf").
' WebView2 renders PDFs with the same built-in viewer as the Edge browser (toolbar, zoom, print).
' Save the IronPDF-generated document to disk first, then point WebView2 at it.
Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")
Dim pdfPath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf")
pdf.SaveAs(pdfPath)
' pdfWebView is the WebView2 control declared in your XAML.
' EnsureCoreWebView2Async must complete before navigating.
Await pdfWebView.EnsureCoreWebView2Async()
pdfWebView.CoreWebView2.Navigate(New Uri(pdfPath).AbsoluteUri)
' Legacy alternative: the older System.Windows.Controls.WebBrowser control still works on
' Windows machines that have a PDF handler installed, but it relies on the deprecated Internet
' Explorer engine and is not recommended for new applications. Prefer WebView2 above.
El Iron Suite juega un papel crucial en nuestras operaciones. Estas son herramientas que aumentan la eficiencia en toda la empresa, incluyendo la creación de planos y la mejora en la gestión de inventario.
¿Cómo veo PDFs en Windows Forms?
Coloca un control WebView2 en tu formulario y apúntalo al PDF guardado, exactamente como en WPF. El control se inicializa de manera asincrónica, así que espera EnsureCoreWebView2Async antes de llamar a Navigate. Esto da a las aplicaciones de WinForms el mismo visor basado en Chromium sin incluir un componente de terceros.
:path=/static-assets/pdf/content-code-examples/how-to/net-pdf-viewer-winforms-viewer.cs
// Windows Forms: display a PDF using the WebView2 control (Microsoft Edge / Chromium).
// Install the NuGet package Microsoft.Web.WebView2, then drag a WebView2 control onto your form
// (or add it in code) and name it pdfWebView.
using System;
using System.IO;
// Generate or load the PDF with IronPDF, then save it so WebView2 can open the file.
var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>");
string pdfPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf");
pdf.SaveAs(pdfPath);
// pdfWebView is the WebView2 control on your form.
// Initialize the runtime, then navigate to the local file URI.
await pdfWebView.EnsureCoreWebView2Async();
pdfWebView.CoreWebView2.Navigate(new Uri(pdfPath).AbsoluteUri);
// Legacy alternative: the System.Windows.Forms.WebBrowser control can host a PDF when a system
// PDF handler is registered, but it uses the deprecated Internet Explorer engine. Use WebView2
// for new projects so the viewer works consistently across modern Windows installs.
Imports System
Imports System.IO
Imports IronPdf
' Generate or load the PDF with IronPDF, then save it so WebView2 can open the file.
Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello IronPDF</h1>")
Dim pdfPath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "document.pdf")
pdf.SaveAs(pdfPath)
' pdfWebView is the WebView2 control on your form.
' Initialize the runtime, then navigate to the local file URI.
Await pdfWebView.EnsureCoreWebView2Async()
pdfWebView.CoreWebView2.Navigate(New Uri(pdfPath).AbsoluteUri)
' Legacy alternative: the System.Windows.Forms.WebBrowser control can host a PDF when a system
' PDF handler is registered, but it uses the deprecated Internet Explorer engine. Use WebView2
' for new projects so the viewer works consistently across modern Windows installs.
Si prefieres no hospedar un control de navegador en absoluto, el enfoque basado en imágenes de la sección anterior se inserta directamente en un PictureBox y evita completamente la dependencia del runtime de WebView2.
¿Cómo veo PDFs en el visor PDF del sistema por defecto?
Pasa la ruta del archivo a System.Diagnostics.Process.Start para abrir el PDF en el lector que el usuario haya configurado como predeterminado, como un navegador o Adobe Acrobat. Esto entrega la renderización a una aplicación externa en lugar de incrustarla, lo que es adecuado para utilidades y herramientas por lotes que solo necesitan mostrar el archivo terminado.
:path=/static-assets/pdf/content-code-examples/how-to/net-pdf-viewer-default-pdf-viewer.cs
using IronPdf;
// Render any HTML fragment or document to HTML
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");
var outputPath = "ChromePdfRenderer.pdf";
// Export PDF document
pdf.SaveAs(outputPath);
// This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(outputPath);
Imports IronPdf
' Render any HTML fragment or document to HTML
Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>")
Private outputPath = "ChromePdfRenderer.pdf"
' Export PDF document
pdf.SaveAs(outputPath)
' This neat trick opens our PDF file so we can see the result in our default PDF viewer
System.Diagnostics.Process.Start(outputPath)
En producción, envuelve la llamada para que un manejador de PDF faltante no haga que la aplicación falle:
try
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
catch (Exception ex)
{
// Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}");
}
try
{
var psi = new System.Diagnostics.ProcessStartInfo
{
FileName = outputPath,
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
catch (Exception ex)
{
// Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}");
}
Imports System.Diagnostics
Imports System.Windows.Forms
Try
Dim psi As New ProcessStartInfo With {
.FileName = outputPath,
.UseShellExecute = True
}
Process.Start(psi)
Catch ex As Exception
' Handle the case where no PDF viewer is installed
MessageBox.Show($"Unable to open PDF: {ex.Message}")
End Try
Conclusión
Cada ruta de visualización aquí intercambia interactividad por portabilidad: el visor MAUI proporciona una barra de herramientas completa, rasterizar a imágenes funciona en cualquier UI en cualquier plataforma, WebView2 reutiliza el motor Edge, y Process.Start delega al lector del usuario. Elige la que coincida con tu aplicación en lugar de forzar una única respuesta.
Como la mayoría de las visualizaciones comienzan con un documento que has generado, acompaña estas técnicas con el tutorial del visor MAUI completo cuando necesites un componente de barra de herramientas interactivo.
Preguntas Frecuentes
¿Cómo puedo mostrar archivos PDF en una aplicación .NET MAUI?
IronPDF incluye un componente visor de PDF interactivo para proyectos MAUI en el paquete NuGet IronPdf.Viewer.Maui. Después de instalar el paquete y llamar a ConfigureIronPdfView(), puedes vincular un PDF a un control IronPdfView, cargándolo desde un archivo con IronPdfViewSource.FromFile o desde un flujo. Este componente MAUI es el único camino que proporciona una barra de herramientas incorporada; en escritorio y web visualizas PDFs alojando WebView2, integrando un iframe, o rasterizando páginas a imágenes.
¿Cuál es la forma más sencilla de ver archivos PDF en aplicaciones web ASP.NET?
Para aplicaciones ASP.NET, IronPDF admite la visualización de archivos PDF a través de ventanas del navegador o iframes. El enfoque iframe es particularmente eficaz, ya que mantiene el diseño de su aplicación mientras muestra el contenido PDF en línea. También puede utilizar las funciones de conversión de HTML a PDF de IronPDF para generar PDF dinámicos sobre la marcha.
¿Puedo integrar la visualización de PDF en aplicaciones WPF y WinForms?
Sí. Para WPF y WinForms, aloja un control WebView2 y navega hacia un PDF guardado; WebView2 usa el motor Chromium de Microsoft Edge e incluye su propia barra de herramientas, zoom e impresión. WebView2 reemplaza el anterior control WebBrowser que dependía del motor obsoleto de Internet Explorer. Si prefieres no alojar un control de navegador, rasteriza cada página a una imagen con RasterizeToImageFiles y muéstrala en una Imagen o PictureBox. IronPDF también maneja firmas digitales, llenado de formularios, y compresión de PDF en los mismos documentos.
¿Es posible utilizar el visor de PDF predeterminado del sistema con aplicaciones .NET?
Por supuesto. IronPDF admite la integración con el visor de PDF predeterminado del sistema mediante System.Diagnostics.Process. Este enfoque le permite abrir archivos PDF en la aplicación PDF preferida del usuario sin dejar de utilizar IronPDF para generar, manipular o preparar los documentos PDF de antemano.
¿Qué otras funciones de PDF están disponibles además de la visualización?
IronPDF ofrece una amplia gama de funcionalidades de PDF incluyendo firmas digitales para la seguridad de documentos, capacidades de llenado de formularios para PDFs interactivos, compresión de PDF para reducir tamaños de archivo, conversión de HTML a PDF para generación de contenido dinámico, y guardado/exportación de PDFs en varios formatos.

