Saltar al pie de página
USANDO IRONPDF

Cómo crear un visor de PDF de ASP.NET Core

Building an ASP.NET Core PDF viewer shouldn't require complex JavaScript libraries or third-party browser plugins. Modern web applications need a reliable way to display PDF files directly in the browser, whether for invoices, reports, or interactive PDF documents. IronPDF simplifies this process by leveraging your browser's built-in PDF viewer capabilities while generating pixel-perfect PDFs on the server side.

In this article, we'll walk you through how to generate and view PDF documents within your ASP.NET Core projects, showing how to create PDF viewer applications that can display any PDF.

What Is an ASP.NET Core PDF Viewer?

An ASP.NET Core PDF viewer enables users to view PDF documents directly within web applications without downloading files to their device. Instead of wrestling with JavaScript-based document viewer components, IronPDF takes a refreshingly simple approach: it generates high-quality PDF files server-side using Chrome's rendering engine, then serves them with the correct headers so browsers automatically display PDF files inline.

This server-side approach means your ASP.NET Core PDF viewer works consistently across all browsers without additional plugins like Adobe Acrobat Reader. Since IronPDF uses the same Chrome engine that powers millions of browsers, your PDF documents render exactly as intended, preserving CSS styles, JavaScript interactions, and complex layouts. The ASP.NET Core PDF integration handles everything from HTML to PDF conversion to secure document delivery with long-term support.

How Do You Install IronPDF in Your Web Application?

Installing IronPDF in your .NET Core web application requires just one NuGet Package Manager command. Open your Package Manager Console in Visual Studio and run:

Install-Package IronPdf

After installation, configure IronPDF in your Program.cs file to set up your license key:

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"; // Start with a free trial key
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"; // Start with a free trial key
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This simple setup gives you access to IronPDF's complete .NET Core PDF viewer functionality. The library automatically handles Chrome engine deployment and provides a clean API for generating and displaying PDF files in your ASP.NET Core applications.

How Can You Create a Basic PDF Document Viewer?

Creating your first ASP.NET Core PDF viewer requires minimal code. Here's a controller that converts HTML content into a viewable PDF document:

using IronPdf;
using Microsoft.AspNetCore.Mvc;

public class PdfController : Controller
{
    public IActionResult ViewDocument()
    {
        var renderer = new ChromePdfRenderer();

        // Create PDF from HTML string
        var html = @"
            <html>
                <body style='font-family: Arial; padding: 20px;'>
                    <h1>Invoice #2024-001</h1>
                    <p>This PDF document is displayed directly in your browser.</p>
                    <table style='width: 100%; border-collapse: collapse;'>
                        <tr>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Item</td>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Price</td>
                        </tr>
                        <tr>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Service</td>
                            <td style='border: 1px solid #ddd; padding: 8px;'>$99.00</td>
                        </tr>
                    </table>
                </body>
            </html>";
        var pdf = renderer.RenderHtmlAsPdf(html);

        // Return PDF for inline viewing
        Response.Headers.Add("Content-Disposition", "inline; filename=invoice.pdf");
        return File(pdf.BinaryData, "application/pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;

public class PdfController : Controller
{
    public IActionResult ViewDocument()
    {
        var renderer = new ChromePdfRenderer();

        // Create PDF from HTML string
        var html = @"
            <html>
                <body style='font-family: Arial; padding: 20px;'>
                    <h1>Invoice #2024-001</h1>
                    <p>This PDF document is displayed directly in your browser.</p>
                    <table style='width: 100%; border-collapse: collapse;'>
                        <tr>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Item</td>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Price</td>
                        </tr>
                        <tr>
                            <td style='border: 1px solid #ddd; padding: 8px;'>Service</td>
                            <td style='border: 1px solid #ddd; padding: 8px;'>$99.00</td>
                        </tr>
                    </table>
                </body>
            </html>";
        var pdf = renderer.RenderHtmlAsPdf(html);

        // Return PDF for inline viewing
        Response.Headers.Add("Content-Disposition", "inline; filename=invoice.pdf");
        return File(pdf.BinaryData, "application/pdf");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

The ChromePdfRenderer class handles the conversion processing, transforming your HTML into a PDF document. Setting the Content-Disposition header to "inline" tells the browser to display the PDF rather than download it, creating a seamless PDF viewer experience where users can view PDF files directly in their web application.

Output PDF Document in Browser Viewer

How to Create an ASP.NET Core PDF Viewer: Figure 1 - PDF in our browser PDF viewer

How Do You Display PDF Files from Different Sources?

Your ASP.NET Core PDF viewer can generate PDF files from multiple package sources. Here's how to convert a URL into a viewable PDF:

public IActionResult ViewFromUrl(string websiteUrl)
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions.EnableJavaScript = true;
    renderer.RenderingOptions.WaitFor.RenderDelay = 2000; // Wait for content to load
    var pdf = renderer.RenderUrlAsPdf(websiteUrl);
    Response.Headers.Add("Content-Disposition", "inline");
    return File(pdf.BinaryData, "application/pdf");
}
public IActionResult ViewFromUrl(string websiteUrl)
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions.EnableJavaScript = true;
    renderer.RenderingOptions.WaitFor.RenderDelay = 2000; // Wait for content to load
    var pdf = renderer.RenderUrlAsPdf(websiteUrl);
    Response.Headers.Add("Content-Disposition", "inline");
    return File(pdf.BinaryData, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Create an ASP.NET Core PDF Viewer: Figure 2 - PDF rendered from URL and displayed in our PDF viewer program

For existing PDF files stored on the server, you can load and display them easily. This sample code shows how to work with files in your wwwroot folder:

public IActionResult ViewExistingPdf(string fileName)
{
    // Load PDF from wwwroot folder
    var pdfPath = Path.Combine(_webHostEnvironment.WebRootPath, "documents", fileName);
    var pdf = PdfDocument.FromFile(pdfPath);   
    // Optional: Add modifications like watermarks
    pdf.ApplyWatermark("<h2 style='color: red; opacity: 0.5;'>CONFIDENTIAL</h2>");
    return File(pdf.BinaryData, "application/pdf");
}
public IActionResult ViewExistingPdf(string fileName)
{
    // Load PDF from wwwroot folder
    var pdfPath = Path.Combine(_webHostEnvironment.WebRootPath, "documents", fileName);
    var pdf = PdfDocument.FromFile(pdfPath);   
    // Optional: Add modifications like watermarks
    pdf.ApplyWatermark("<h2 style='color: red; opacity: 0.5;'>CONFIDENTIAL</h2>");
    return File(pdf.BinaryData, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How to Create an ASP.NET Core PDF Viewer: Figure 3 - Viewing an Existing PDF (With our added watermark)

This flexibility means your PDF viewer can handle both dynamically generated content and existing PDF documents stored in your wwwroot folder or database. The component seamlessly integrates with your ASP.NET Core architecture.

How Can You Add Advanced PDF Viewer Features?

IronPDF transforms your basic PDF viewer into a powerful document viewer with advanced capabilities. Adding forms to your PDF files enables interactive functionality that users can fill directly:

public IActionResult CreateFormPdf()
{
    var html = @"
        <html>
            <body>
                <h2>Application Form</h2>
                <form>
                    Name: 
                    <br><br>
                    Email: 
                    <br><br>
                    <input type='checkbox'> I agree to terms
                </form>
            </body>
        </html>";
    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.CreatePdfFormsFromHtml = true; // Enable form fields
    var pdf = renderer.RenderHtmlAsPdf(html);
    return File(pdf.BinaryData, "application/pdf");
}
public IActionResult CreateFormPdf()
{
    var html = @"
        <html>
            <body>
                <h2>Application Form</h2>
                <form>
                    Name: 
                    <br><br>
                    Email: 
                    <br><br>
                    <input type='checkbox'> I agree to terms
                </form>
            </body>
        </html>";
    var renderer = new ChromePdfRenderer();
    renderer.RenderingOptions.CreatePdfFormsFromHtml = true; // Enable form fields
    var pdf = renderer.RenderHtmlAsPdf(html);
    return File(pdf.BinaryData, "application/pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output with Fillable Form

How to Create an ASP.NET Core PDF Viewer: Figure 4

When users open this PDF in their browser, they can fill out the forms directly without needing external tools. You can also edit PDF files by adding headers, footers, page numbers, or digital signatures. The tag helper approach makes it easy to add these features:

// Add headers and page numbers
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center;'>Company Report</div>",
    MaxHeight = 25
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center;'>Page {page} of {total-pages}</div>",
    MaxHeight = 25
};
// Add headers and page numbers
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center;'>Company Report</div>",
    MaxHeight = 25
};
renderer.RenderingOptions.HtmlFooter = new HtmlHeaderFooter()
{
    HtmlFragment = "<div style='text-align: center;'>Page {page} of {total-pages}</div>",
    MaxHeight = 25
};
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

These features transform your ASP.NET PDF viewer into a comprehensive solution for document management, supporting everything from simple display to complex editing operations, including text selection and print functionality. You can even work with other formats like Excel, Word, DOCX files, and PowerPoint through IronPDF's conversion capabilities.

Conclusion

Creating an ASP.NET Core PDF viewer with IronPDF eliminates the complexity of JavaScript-based solutions while providing professional-grade PDF document handling. By leveraging the browser's native capabilities and Chrome's rendering engine, you can create, display, and manage PDF files with just a few lines of code—no default configurations or complex setup required.

The combination of server-side generation and browser-based viewing provides the perfect balance of support, performance, and user experience for your web applications. Whether you need to display PDF files, handle forms, edit existing documents, or print PDFs, IronPDF's straightforward API makes implementation simple. The library is frequently updated to ensure compatibility with the latest .NET frameworks and Windows environments.

Ready to build your own PDF viewer in your ASP.NET Core project? Start with a free trial to find the right plan. Need help getting started? Check out this detailed tutorial or browse the complete documentation for more examples.

Preguntas Frecuentes

¿Cuál es el propósito de un visor de PDF ASP.NET Core?

Un visor de PDF ASP.NET Core le permite mostrar archivos PDF directamente en el navegador, facilitando a los usuarios ver documentos como facturas, informes o PDFs interactivos sin necesidad de complementos externos.

¿Cómo simplifica IronPDF la creación de un visor de PDF en ASP.NET Core?

IronPDF simplifica el proceso aprovechando las capacidades de visor de PDF integradas del navegador y generando PDFs perfectamente detallados en el lado del servidor, eliminando la necesidad de bibliotecas de JavaScript complejas o complementos de terceros.

¿Puede IronPDF manejar documentos PDF interactivos?

Sí, IronPDF puede gestionar documentos PDF interactivos, permitiendo a los usuarios rellenar formularios e interactuar con contenido PDF directamente en el navegador.

¿Cuáles son los beneficios de usar IronPDF para mostrar PDFs en aplicaciones web?

IronPDF proporciona una manera confiable y eficiente de mostrar PDFs en aplicaciones web, ofreciendo características como generación de PDF en el lado del servidor e integración perfecta con aplicaciones ASP.NET Core.

¿Es necesario usar complementos de navegador de terceros con IronPDF?

No, IronPDF utiliza las capacidades de visor de PDF integradas del navegador, por lo que no hay necesidad de complementos de navegador de terceros para mostrar archivos PDF.

¿Qué tipos de documentos PDF pueden mostrarse con un visor de PDF ASP.NET Core?

Un visor de PDF ASP.NET Core puede mostrar varios tipos de documentos PDF, incluidos facturas, informes y formularios interactivos, directamente en el navegador.

¿IronPDF soporta la generación de PDF en el lado del servidor?

Sí, IronPDF soporta la generación de PDF en el lado del servidor, asegurando que los documentos se rendericen de manera precisa y eficiente antes de ser mostrados en el navegador.

¿Cómo asegura IronPDF un renderizado de PDF perfecto?

IronPDF asegura una renderización de PDF perfectamente detallada utilizando algoritmos avanzados y técnicas para reproducir fielmente la apariencia de documentos generados en el lado del servidor.

¿Qué lenguaje de programación se utiliza para construir un visor de PDF ASP.NET Core con IronPDF?

El visor de PDF ASP.NET Core se construye utilizando C# y el marco ASP.NET Core, aprovechando IronPDF para manejar el procesamiento y la visualización de PDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más