跳至页脚内容
使用IRONPDF

如何使用 IronPDF for .NET 创建 ASP.NET Core MVC PdfViewer

使用 IronPDF 基于 Chrome 的渲染引擎创建一个 ASP.NET Core MVC PDF 查看器,以在浏览器中内联显示 PDF 文件,从 HTML 内容生成动态 PDF,并控制用户是查看还是下载文档——所有这些都不需要外部插件或依赖项。

现代浏览器包含一个内置 PDF 查看器,当网络应用程序提供具有正确 MIME 类型的 PDF 文件时,该浏览器会自动激活。 这样就不需要第三方工具或插件,用户可以直接在浏览器中显示 PDF 文档。 IronPDF是一个经常更新的 .NET PDF 库,它使在 ASP.NET Core MVC 应用程序中生成、渲染和显示 PDF 文件变得简单。

在本文中,我们将向您展示如何使用 IronPDF 的基于 Chrome 的渲染引擎创建一个 ASP.NET Core MVC PDF 查看器 Web 应用程序。 本指南的主要重点是在保持高性能的同时,实现像素级的完美效果

立即开始使用 IronPDF。
green arrow pointer

现代浏览器如何显示 PDF 文件?

Chrome、Firefox、Edge 和 Safari 等现代浏览器都包含本地 PDF 浏览器功能。 当您的 ASP.NET Core 应用程序返回具有 application/pdf 内容类型的文件时,浏览器会内嵌渲染 PDF 文档,而无需使用 Adobe Acrobat 或外部插件。 该内置 PDF 查看器支持文本选择、打印、缩放控制、书签和页面导航等基本功能,可创建完整的文档查看体验。

为了安全地提供现有文件,最佳实践是使用托管环境来定位它们,而不是依赖开发和生产之间可能会发生变化的目录路径。 此外,对于大型文档,使用文件流通常比加载整个字节数组更节省内存。

using Microsoft.AspNetCore.Mvc;
public class DocumentController : Controller
{
    public IActionResult ViewPdf()
    {
        // Path to an existing PDF file in the wwwroot folder
        string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "documents", "sample.pdf");
        byte[] fileBytes = System.IO.File.ReadAllBytes(path);
        // Return file for inline browser display
        return File(fileBytes, "application/pdf");
    }
}
using Microsoft.AspNetCore.Mvc;
public class DocumentController : Controller
{
    public IActionResult ViewPdf()
    {
        // Path to an existing PDF file in the wwwroot folder
        string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "documents", "sample.pdf");
        byte[] fileBytes = System.IO.File.ReadAllBytes(path);
        // Return file for inline browser display
        return File(fileBytes, "application/pdf");
    }
}
Imports Microsoft.AspNetCore.Mvc

Public Class DocumentController
    Inherits Controller

    Public Function ViewPdf() As IActionResult
        ' Path to an existing PDF file in the wwwroot folder
        Dim path As String = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "documents", "sample.pdf")
        Dim fileBytes As Byte() = System.IO.File.ReadAllBytes(path)
        ' Return file for inline browser display
        Return File(fileBytes, "application/pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

这种简单的方法可以有效地提供存储在服务器上的静态 PDF 文件。 对于更高级的场景,您可能需要从内存Azure Blob 存储加载 PDF,这样可以提高可扩展性并减少服务器存储需求。

PDF文件在浏览器中显示时是什么样子?

一个关于"什么是 PDF?"的 PDF 文档在本地主机 7162/Pdf/ViewPdf 的网页浏览器中显示,以 PDF 查看器界面呈现格式化的文本内容,并带有缩放控件和导航选项。

上面的代码从服务器读取现有的 PDF 文件并返回给浏览器。 File() 方法接受一个字节数组和一个内容类型,指示浏览器的文档查看器以内联方式呈现内容。这种方法适用于台式机和移动设备上的所有现代浏览器,为所有用户提供一致的体验。

开发人员如何动态生成 PDF 文档?

静态 PDF 文件很有用,但许多网络应用程序需要动态生成的文档。 IronPDF 的 ChromePdfRenderer 类可将 HTML 内容转换为专业渲染的 PDF 文件。 首先,通过 Visual Studio 中的NuGet 包安装 IronPDF 即可开始使用。

您可以直接在 HTML 字符串中包含外部资源,例如特定主题的 CSS图表的 JavaScript 。 渲染引擎支持现代网络标准,包括 CSS3、JavaScript ES6+ 和网络字体

using IronPdf;
using Microsoft.AspNetCore.Mvc;
public class ReportController : Controller
{
    public IActionResult GenerateReport()
    {
        var renderer = new ChromePdfRenderer();
        // HTML content with CSS styling
        string html = @"
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; padding: 40px; }
                    h1 { color: #2c3e50; }
                    .report-body { line-height: 1.6; }
                </style>
            </head>
            <body>
                <h1>Monthly Sales Report</h1>
                <div class='report-body'>
                    <p>Generated: " + DateTime.Now.ToString("MMMM dd, yyyy") + @"</p>
                    <p>This report contains the latest sales figures.</p>
                </div>
            </body>
            </html>";
        PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
        return File(pdf.BinaryData, "application/pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
public class ReportController : Controller
{
    public IActionResult GenerateReport()
    {
        var renderer = new ChromePdfRenderer();
        // HTML content with CSS styling
        string html = @"
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; padding: 40px; }
                    h1 { color: #2c3e50; }
                    .report-body { line-height: 1.6; }
                </style>
            </head>
            <body>
                <h1>Monthly Sales Report</h1>
                <div class='report-body'>
                    <p>Generated: " + DateTime.Now.ToString("MMMM dd, yyyy") + @"</p>
                    <p>This report contains the latest sales figures.</p>
                </div>
            </body>
            </html>";
        PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
        return File(pdf.BinaryData, "application/pdf");
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc

Public Class ReportController
    Inherits Controller

    Public Function GenerateReport() As IActionResult
        Dim renderer As New ChromePdfRenderer()
        ' HTML content with CSS styling
        Dim html As String = "
            <html>
            <head>
                <style>
                    body { font-family: Arial, sans-serif; padding: 40px; }
                    h1 { color: #2c3e50; }
                    .report-body { line-height: 1.6; }
                </style>
            </head>
            <body>
                <h1>Monthly Sales Report</h1>
                <div class='report-body'>
                    <p>Generated: " & DateTime.Now.ToString("MMMM dd, yyyy") & "</p>
                    <p>This report contains the latest sales figures.</p>
                </div>
            </body>
            </html>"
        Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
        Return File(pdf.BinaryData, "application/pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

PDF生成后,HTML内容会如何显示?

! PDF 查看器显示一份月度销售报告,其中包含格式化的标题文本和生成日期,演示了通过 IronPDF 将 HTML 转换为 PDF 并应用自定义 CSS 样式的过程。

此示例演示了 IronPDF 如何将HTML 字符串转换为 PDF文档。 ChromePdfRenderer 使用基于 Chromium 的引擎,可确保准确的 CSS 呈现和 JavaScript 支持。 生成的 PDF 文件保留了 HTML 中定义的所有样式,因此非常适合创建报告发票和其他需要一致格式的文档。 控制器处理请求并将渲染后的输出返回给用户。

有关HTML 转 PDF 转换的更多信息和代码示例,请查阅 IronPDF 的综合文档。 您还可以从CSHTML Razor 视图URL甚至Markdown 内容生成 PDF。

内联显示与下载有哪些选项?

有时用户需要下载 PDF 文件,而不是在浏览器中查看。 您可能会在主页上设置一个链接,引导用户访问这些报告。 浏览器如何处理响应取决于Content-Disposition标头。 理解这种区别对于提供正确的用户体验至关重要。

using IronPdf;
using Microsoft.AspNetCore.Mvc;
public class PdfController : Controller
{
    public IActionResult DisplayInline()
    {
        var renderer = new ChromePdfRenderer();
        // Configure rendering options for better output
        renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
        renderer.RenderingOptions.MarginTop = 25;
        renderer.RenderingOptions.MarginBottom = 25;

        PdfDocument pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_42___");
        // Display PDF inline in browser
        return File(pdf.BinaryData, "application/pdf");
    }

    public IActionResult DownloadPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Set additional options for downloaded PDFs
        renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
        renderer.RenderingOptions.EnableJavaScript = true;

        PdfDocument pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_43___");
        // Prompt download with specified filename
        return File(pdf.BinaryData, "application/pdf", "webpage-report.pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
public class PdfController : Controller
{
    public IActionResult DisplayInline()
    {
        var renderer = new ChromePdfRenderer();
        // Configure rendering options for better output
        renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait;
        renderer.RenderingOptions.MarginTop = 25;
        renderer.RenderingOptions.MarginBottom = 25;

        PdfDocument pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_42___");
        // Display PDF inline in browser
        return File(pdf.BinaryData, "application/pdf");
    }

    public IActionResult DownloadPdf()
    {
        var renderer = new ChromePdfRenderer();
        // Set additional options for downloaded PDFs
        renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter;
        renderer.RenderingOptions.EnableJavaScript = true;

        PdfDocument pdf = renderer.RenderUrlAsPdf("___PROTECTED_URL_43___");
        // Prompt download with specified filename
        return File(pdf.BinaryData, "application/pdf", "webpage-report.pdf");
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc

Public Class PdfController
    Inherits Controller

    Public Function DisplayInline() As IActionResult
        Dim renderer As New ChromePdfRenderer()
        ' Configure rendering options for better output
        renderer.RenderingOptions.PaperOrientation = PdfPaperOrientation.Portrait
        renderer.RenderingOptions.MarginTop = 25
        renderer.RenderingOptions.MarginBottom = 25

        Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("___PROTECTED_URL_42___")
        ' Display PDF inline in browser
        Return File(pdf.BinaryData, "application/pdf")
    End Function

    Public Function DownloadPdf() As IActionResult
        Dim renderer As New ChromePdfRenderer()
        ' Set additional options for downloaded PDFs
        renderer.RenderingOptions.PaperSize = PdfPaperSize.Letter
        renderer.RenderingOptions.EnableJavaScript = True

        Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("___PROTECTED_URL_43___")
        ' Prompt download with specified filename
        Return File(pdf.BinaryData, "application/pdf", "webpage-report.pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

何时应该使用内联显示而不是下载显示?

屏幕截图显示了维基百科主页转换为 PDF 格式后,在浏览器窗口中以内嵌方式显示,并带有 PDF 查看器控件,包括缩放、页面导航和打印选项。

这两个控制器操作的区别在于 File() 方法的第三个参数。 当您提供文件名时,ASP.NET Core 会自动添加Content-Disposition: attachment标头,提示用户下载文件。如果省略文件名参数,则使用默认的内联显示模式。

这种灵活性使您的应用程序能够根据用户需求或项目要求支持不同的查看场景。 为了增强控制,您还可以实现自定义页眉或配置纸张尺寸方向设置

Razor Pages 如何与 .NET Core PDF 生成集成?

ASP.NET Core MVC 中的 Razor Pages 为实现 .NET PDF 查看器提供了另一种方法。 页面模型可以使用相同的 IronPDF 功能生成和返回 PDF 文件。 这种模式对于已经使用 Razor Pages 作为其架构的应用程序来说尤其有效。

using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class InvoiceModel : PageModel
{
    public IActionResult OnGet(int id)
    {
        var renderer = new ChromePdfRenderer();
        // Configure rendering options
        renderer.RenderingOptions.MarginTop = 20;
        renderer.RenderingOptions.MarginBottom = 20;
        renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

        // Add header and footer
        renderer.RenderingOptions.TextHeader.CenterText = "Invoice Document";
        renderer.RenderingOptions.TextFooter.RightText = "Page {page} of {total-pages}";
        renderer.RenderingOptions.TextFooter.FontSize = 10;

        string html = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: 'Segoe UI', Arial, sans-serif; padding: 40px; }}
                    h1 {{ color: #1a5490; border-bottom: 2px solid #1a5490; padding-bottom: 10px; }}
                    .invoice-details {{ margin: 20px 0; }}
                    table {{ width: 100%; border-collapse: collapse; }}
                    th, td {{ padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }}
                </style>
            </head>
            <body>
                <h1>Invoice #{id}</h1>
                <div class='invoice-details'>
                    <p><strong>Date:</strong> {DateTime.Now:yyyy-MM-dd}</p>
                    <p><strong>Due Date:</strong> {DateTime.Now.AddDays(30):yyyy-MM-dd}</p>
                </div>
                <table>
                    <tr>
                        <th>Description</th>
                        <th>Amount</th>
                    </tr>
                    <tr>
                        <td>Professional Services</td>
                        <td>$1,500.00</td>
                    </tr>
                </table>
                <p style='margin-top: 40px;'>Thank you for your business!</p>
            </body>
            </html>";

        PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
        return File(pdf.BinaryData, "application/pdf");
    }
}
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class InvoiceModel : PageModel
{
    public IActionResult OnGet(int id)
    {
        var renderer = new ChromePdfRenderer();
        // Configure rendering options
        renderer.RenderingOptions.MarginTop = 20;
        renderer.RenderingOptions.MarginBottom = 20;
        renderer.RenderingOptions.PaperSize = PdfPaperSize.A4;

        // Add header and footer
        renderer.RenderingOptions.TextHeader.CenterText = "Invoice Document";
        renderer.RenderingOptions.TextFooter.RightText = "Page {page} of {total-pages}";
        renderer.RenderingOptions.TextFooter.FontSize = 10;

        string html = $@"
            <html>
            <head>
                <style>
                    body {{ font-family: 'Segoe UI', Arial, sans-serif; padding: 40px; }}
                    h1 {{ color: #1a5490; border-bottom: 2px solid #1a5490; padding-bottom: 10px; }}
                    .invoice-details {{ margin: 20px 0; }}
                    table {{ width: 100%; border-collapse: collapse; }}
                    th, td {{ padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }}
                </style>
            </head>
            <body>
                <h1>Invoice #{id}</h1>
                <div class='invoice-details'>
                    <p><strong>Date:</strong> {DateTime.Now:yyyy-MM-dd}</p>
                    <p><strong>Due Date:</strong> {DateTime.Now.AddDays(30):yyyy-MM-dd}</p>
                </div>
                <table>
                    <tr>
                        <th>Description</th>
                        <th>Amount</th>
                    </tr>
                    <tr>
                        <td>Professional Services</td>
                        <td>$1,500.00</td>
                    </tr>
                </table>
                <p style='margin-top: 40px;'>Thank you for your business!</p>
            </body>
            </html>";

        PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
        return File(pdf.BinaryData, "application/pdf");
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages

Public Class InvoiceModel
    Inherits PageModel

    Public Function OnGet(id As Integer) As IActionResult
        Dim renderer As New ChromePdfRenderer()
        ' Configure rendering options
        renderer.RenderingOptions.MarginTop = 20
        renderer.RenderingOptions.MarginBottom = 20
        renderer.RenderingOptions.PaperSize = PdfPaperSize.A4

        ' Add header and footer
        renderer.RenderingOptions.TextHeader.CenterText = "Invoice Document"
        renderer.RenderingOptions.TextFooter.RightText = "Page {page} of {total-pages}"
        renderer.RenderingOptions.TextFooter.FontSize = 10

        Dim html As String = $"
            <html>
            <head>
                <style>
                    body {{ font-family: 'Segoe UI', Arial, sans-serif; padding: 40px; }}
                    h1 {{ color: #1a5490; border-bottom: 2px solid #1a5490; padding-bottom: 10px; }}
                    .invoice-details {{ margin: 20px 0; }}
                    table {{ width: 100%; border-collapse: collapse; }}
                    th, td {{ padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }}
                </style>
            </head>
            <body>
                <h1>Invoice #{id}</h1>
                <div class='invoice-details'>
                    <p><strong>Date:</strong> {DateTime.Now:yyyy-MM-dd}</p>
                    <p><strong>Due Date:</strong> {DateTime.Now.AddDays(30):yyyy-MM-dd}</p>
                </div>
                <table>
                    <tr>
                        <th>Description</th>
                        <th>Amount</th>
                    </tr>
                    <tr>
                        <td>Professional Services</td>
                        <td>$1,500.00</td>
                    </tr>
                </table>
                <p style='margin-top: 40px;'>Thank you for your business!</p>
            </body>
            </html>"

        Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
        Return File(pdf.BinaryData, "application/pdf")
    End Function
End Class
$vbLabelText   $csharpLabel

PDF自定义有哪些渲染选项?

PDF 查看器以专业格式显示第 20 号发票,包括样式化的标题、到期日信息和感谢信息,并在深色主题浏览器界面中显示

此 Razor Pages 示例演示了OnGet处理程序如何根据 URL 参数生成 PDF。 RenderingOptions属性允许自定义边距、页面方向和其他设置。 您还可以添加页眉和页脚,配置页码,或设置自定义纸张尺寸。 如需了解更多信息,请查阅 IronPDF 的渲染选项文档

高级功能包括水印PDF压缩数字签名。 您还可以实现表单创建合并多个 PDF 文件,以实现更复杂的文档工作流程。

构建 PDF 查看器的关键要点是什么?

为 PDF 文档创建一个 ASP.NET Core MVC 浏览器,将浏览器原生功能与 IronPDF 强大的生成功能相结合。 现代浏览器中内置的 PDF 查看器会在 ASP.NET 控制器返回具有正确 MIME 类型的文件时自动处理显示、打印和导航功能。 IronPdf 简化了从 HTML、URL 或现有文件创建专业 PDF 文档的过程,完全支持 CSS、JavaScript 和自定义渲染选项。

在 ASP.NET Core 中使用 IronPDF 查看 PDF 文件的主要优势包括:

  • 无需外部查看器插件 Chrome渲染引擎确保HTML/CSS渲染的准确性
  • 支持 JavaScript 和动态内容
  • 提供灵活的在线查看和文件下载选项
  • 提供丰富的自定义选项,实现专业输出
  • 跨平台支持,包括 Linux 和 Docker

无论是构建用于显示 PDF 文件的简单文档查看器,还是实现完整的报表生成系统,IronPDF 都提供了无缝 PDF 集成所需的工具和功能。 该库可与您的 ASP.NET Core Web 应用程序无缝集成,同时支持传统的 MVC 控制器和现代的 Razor Pages 方法。

对于生产环境部署,请考虑异步渲染和适当的内存管理性能优化技术。 您还可以探索高级功能,例如用于长期存档的PDF/A 合规性或用于敏感文档的PDF 安全性

立即开始免费试用,探索 IronPDF 的全部功能,或购买许可证用于生产环境。 请访问我们的完整文档,了解更多高级功能和最佳实践。

常见问题解答

如何在 ASP.NET Core MVC 应用程序中显示 PDF 文件?

您可以通过 IronPDF for .NET 在 ASP.NET Core MVC 应用程序中显示 PDF 文件。它允许您使用现代内置 PDF 查看器直接在浏览器中生成、渲染和显示 PDF 文件。

在浏览器中查看 PDF 是否需要第三方插件?

不,现代浏览器已内置了 PDF 浏览器,在提供具有正确 MIME 类型的 PDF 文件时会自动激活。IronPDF 可帮助确保您的 PDF 得到正确的服务。

在 ASP.NET Core MVC 中使用 IronPDF 的优势是什么?

IronPDF for .NET 是一个 .NET PDF 库,可简化在 ASP.NET Core MVC 应用程序中生成和渲染 PDF 文档的过程,提高工作效率并简化 PDF 管理。

IronPDF 能否与现有的浏览器 PDF 查看器一起使用?

是的,IronPDF 可与现有的浏览器 PDF 查看器无缝配合,确保 PDF 文件以正确的 MIME 类型提供,以便在浏览器中自动显示。

IronPdf 是否经常更新?

是的,IronPDF 是一个经常更新的 .NET PDF 库,为在 ASP.NET Core MVC 应用程序中处理 PDF 文档提供了最新的功能和改进。

IronPDF 如何处理网络应用程序中的 PDF 生成?

IronPDF 提供了从各种内容类型生成 PDF 的强大功能,允许开发人员在网络应用程序中创建动态和交互式 PDF 文档。

PDF 文件应使用哪种 MIME 类型?

为确保在浏览器中正确显示,PDF 文件应以 MIME 类型 "application/pdf "提供。IronPDF 可协助高效管理这方面的工作。

我可以在 IronPDF 中自定义 PDF 渲染吗?

是的,IronPDF 为渲染 PDF 提供了广泛的自定义选项,允许您定制输出以满足特定的设计和功能要求。

IronPDF 是否仅支持 ASP.NET Core MVC 应用程序?

虽然 IronPDF 在 ASP.NET Core MVC 应用程序中表现出色,但它也具有多功能性,可以与其他 .NET 应用程序一起使用,处理 PDF 功能。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。