푸터 콘텐츠로 바로가기
IRONPDF 사용

How to Display a PDF File in ASP.NET Core

PDF files are widely used for document sharing and data display purposes. In web applications, it is often required to display PDF files to users directly within the browser. ASP.NET Core applications provide various options to achieve this functionality, and one popular library for working with PDF files is IronPDF.

IronPDF is a powerful .NET library that allows developers to create, edit, and manipulate PDFs with ease. This article is going to explore how to use IronPDF to display PDF files in an ASP.NET Core PDF viewer application. It will cover the steps to set up the necessary components and provide sample logic to demonstrate the ASP.NET Core PDF viewer integration.

Setting up the Environment

To get started, make sure you have the following prerequisites:

  1. Visual Studio: Install the latest version of Visual Studio or any other compatible Integrated Development Environment (IDE) of your choice.
  2. IronPDF Library: Obtain the IronPDF library from the Official IronPDF Website or via NuGet Package Manager.

    How to Display a PDF File in ASP.NET Core, Figure 1: NuGet Package Manager NuGet Package Manager

  3. .NET Core Application: Make sure you have a basic understanding of ASP.NET Core Setup Instructions and have it installed on your development machine.

Once you have set up the environment, let's dive into the steps to display PDF files using IronPDF in an ASP.NET Core application.

Creating a New Project

  1. Open Visual Studio and create a new ASP.NET Core Web App project.

    How to Display a PDF File in ASP.NET Core, Figure 2: Web Application Web Application

  2. Select the "ASP.NET Core Web App" template.

    How to Display a PDF File in ASP.NET Core, Figure 3: .NET Framework .NET Framework

  3. Choose the desired project settings and click "Create" to generate the new project.

Adding IronPDF Library

To use IronPDF in your project, you need to add the IronPDF library reference.

  1. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages for Solution..."

    How to Display a PDF File in ASP.NET Core, Figure 4: NuGet Package Manager NuGet Package Manager

  2. Search for "IronPDF" in the NuGet Package Manager and install the latest version of the package.

    How to Display a PDF File in ASP.NET Core, Figure 5: NuGet Package Manager - Solution Explorer NuGet Package Manager - Solution Explorer

Create PDF using an ASP.NET Core Web Page

To create a PDF from an ASP.NET Core Web Page from the server side, follow these steps:

How to Display a PDF File in ASP.NET Core, Figure 6: NuGet Package Manager - Solution Explorer Solution Explorer

Step 1 Add the IronPDF Namespace

Open the source file path of the ASP.NET Core web page that you want to convert into a PDF. In the code-behind file (Index.cshtml.cs), add the IronPdf namespace at the top:

using IronPdf;
using IronPdf;
$vbLabelText   $csharpLabel

Step 2 Convert Razor Page to PDF

Inside the OnGet function, add the following code:

public FileContentResult OnGet()
{
    // Create a new instance of ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the current Razor page to a PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    // Add HTTP header to display PDF in the browser
    Response.Headers.Add("Content-Disposition", "inline");

    // Return the PDF file to the client
    return File(pdf.BinaryData, "application/pdf");
}
public FileContentResult OnGet()
{
    // Create a new instance of ChromePdfRenderer
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the current Razor page to a PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    // Add HTTP header to display PDF in the browser
    Response.Headers.Add("Content-Disposition", "inline");

    // Return the PDF file to the client
    return File(pdf.BinaryData, "application/pdf");
}
$vbLabelText   $csharpLabel

With just one line of code, the Razor Page will be converted into a PDF document using the RenderRazorToPdf method.

To achieve this, the IronPdf.Extensions.Razor NuGet Package needs to be installed.

Step 3 Display or Download PDF

By default, the code will display the PDF document in the browser. If you want to download the PDF instead, modify the code as follows:

return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
return File(pdf.BinaryData, "application/pdf", "razorPageToPDF.pdf");
$vbLabelText   $csharpLabel

This code will download the PDF file of the ASP.NET Web Page into your local "Downloads" folder.

How to Display a PDF File in ASP.NET Core, Figure 7: ASPX Page to PDF Razor Page to PDF

Load and Display a PDF file in ASP.NET Core

Next, this section will explore different approaches to generate PDF files using IronPDF and display them in an ASP.NET Core application.

Generate PDF from URL

IronPDF simplifies the process of creating a PDF document by generating an HTML file from a URL (HTTP services) and converting it to a PDF. The following code demonstrates how to generate a PDF file from a URL:

// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");

// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from a URL
using var pdf = new IronPdf.ChromePdfRenderer().RenderUrlAsPdf("https://www.google.co.in/");

// Read the File as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
$vbLabelText   $csharpLabel

In the above code, IronPDF's ChromePdfRenderer class is used to render the HTML content from the specified URL and convert it into a PDF document. The PDF document is then converted to a byte array and sent to the client as a base64 string.

Generate PDF from HTML String

IronPDF offers an efficient approach to transforming HTML strings into PDF documents. The code snippet below demonstrates how to generate a PDF file from a string:

// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
// Render a PDF from an HTML string
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello world!!</h1>");
$vbLabelText   $csharpLabel

In the above example, the RenderHtmlAsPdf method is used to render the HTML string and convert it into a PDF document. The resulting PDF can be further processed or saved as per the application's requirements.

How to Display a PDF File in ASP.NET Core, Figure 8: Web Application Output Web Application Output

Generate PDF from HTML Files

IronPDF also supports transforming HTML files or CSS files into PDF document examples. The following code showcases how to generate a PDF file from an HTML file:

// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");

// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
// Render a PDF from an HTML file
using var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlFileAsPdf("demo.html");

// Read the file as Byte Array
byte[] bytes = pdf.BinaryData;

// Convert File to Base64 string and send to Client
string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
return Content(base64);
$vbLabelText   $csharpLabel

In the code snippet above, the RenderHtmlFileAsPdf method is used to render the HTML content from the specified filename and convert it into a PDF document. The resulting PDF is converted to a byte array and sent to the client as a base64 string.

How to Display a PDF File in ASP.NET Core: Figure 9 - Add a New Web Page

Converting ASP.NET Web Forms to a PDF File with IronPDF from the ASP.NET Web API

You can easily convert ASP.NET web forms to PDF format using just a single line of code instead of HTML. Place this code in the Page_Load method of the page's code-behind file to display it on the page.

Import the IronPdf Namespace

Use the using keyword to import the IronPdf namespace in your code-behind file.

using IronPdf;
using System;
using System.Web.UI;
using IronPdf;
using System;
using System.Web.UI;
$vbLabelText   $csharpLabel

Convert ASP.NET Web Form to PDF

In the code-behind file of the page you want to convert to PDF (e.g., Default.aspx.cs), add the following code:

namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Convert the ASPX page to a PDF displayed in the browser
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
namespace WebApplication7
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Convert the ASPX page to a PDF displayed in the browser
            AspxToPdf.RenderThisPageAsPdf(AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
$vbLabelText   $csharpLabel

The RenderThisPageAsPdf method of the AspxToPdf class will convert the web form into a PDF document from the web API.

Apply HTML Templates

For intranet and website developers, generating PDFs with templates is often a common requirement. IronPDF simplifies this process by allowing you to generate an HTML template and populate it with data.

Here's an example of how to generate multiple customized PDFs using HTML templates and IronPDF:

// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    // Replace placeholder in template with actual data
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

    // Render HTML to PDF
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        // Save the PDF with the name as filename
        Pdf.SaveAs(name + ".pdf");
    }
}
// Define an HTML template with placeholders
string HtmlTemplate = "<p>[[NAME]]</p>";
string[] Names = { "John", "James", "Jenny" };
foreach (var name in Names)
{
    // Replace placeholder in template with actual data
    string HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);

    // Render HTML to PDF
    using (var Pdf = Renderer.RenderHtmlAsPdf(HtmlInstance))
    {
        // Save the PDF with the name as filename
        Pdf.SaveAs(name + ".pdf");
    }
}
$vbLabelText   $csharpLabel

ASP MVC Routing Download the PDF Version Of This Page

If you're using ASP.NET MVC, you can easily direct users to a PDF file. Here's an example of how the source code should be written:

using IronPdf;
using System;
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // Create a new instance of ChromePdfRenderer
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the URL as a PDF
            using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                // Return the PDF file with a specified filename
                return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
            }
        }
        // Other action methods...
    }
}
using IronPdf;
using System;
using System.Web.Mvc;

namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // Create a new instance of ChromePdfRenderer
            ChromePdfRenderer renderer = new ChromePdfRenderer();

            // Render the URL as a PDF
            using (var PDF = renderer.RenderUrlAsPdf(new Uri("https://en.wikipedia.org")))
            {
                // Return the PDF file with a specified filename
                return File(PDF.BinaryData, "application/pdf", "Wiki.Pdf");
            }
        }
        // Other action methods...
    }
}
$vbLabelText   $csharpLabel

Add a Cover Page to a PDF Document

To add a cover page or back page to an existing PDF document, you can use IronPDF's merge functionality. Here's an example:

using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
    // Merge the cover page with the main PDF
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        // Save the combined PDF
        Merged.SaveAs("Combined.Pdf");
    }
}
using (var PDF = Renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf/"))
{
    // Merge the cover page with the main PDF
    using (var Merged = PdfDocument.Merge(new PdfDocument("CoverPage.pdf"), PDF))
    {
        // Save the combined PDF
        Merged.SaveAs("Combined.Pdf");
    }
}
$vbLabelText   $csharpLabel

Add a Watermark to Your Document

You can also add a watermark to PDF documents using C# code. Here's an example:

using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    // Add watermark text to all pages
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);

    // Save the watermarked PDF
    pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render the URL as a PDF
using (var pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf"))
{
    // Add watermark text to all pages
    pdf.WatermarkAllPages("<h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45);

    // Save the watermarked PDF
    pdf.SaveAs(@"C:\PathToWatermarked.pdf");
}
$vbLabelText   $csharpLabel

Protect Your PDF with a Password

You can encrypt and protect a PDF document with a password using IronPDF. Here's an example:

using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    // Set a password to protect the PDF
    pdfDocument.Password = "strong!@#pass&^%word";

    // Save the secured PDF
    pdfDocument.SaveAs("secured.pdf");
}
using IronPdf;

// Create a new instance of ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render HTML to PDF
using (var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello World<h1>"))
{
    // Set a password to protect the PDF
    pdfDocument.Password = "strong!@#pass&^%word";

    // Save the secured PDF
    pdfDocument.SaveAs("secured.pdf");
}
$vbLabelText   $csharpLabel

In addition to the above functionalities, IronPDF offers other features such as extracting images and text with OCR from PDFs, rendering charts to PDF, adding barcodes to PDFs, enhancing document security with passwords and watermarking techniques for PDFs, even handling and customizing PDF forms, and more. By using IronPDF, you can simplify the process of creating PDFs and improve the overall presentation of your documents.

Conclusion

IronPDF is an exceptional tool designed specifically for .NET developers, offering a wide range of functionalities to effortlessly handle PDF manipulation within their .NET projects. With IronPDF, developers can enhance their workflow and streamline their work processes. This powerful tool provides numerous features that enable seamless PDF file formatting, page deletion, page addition, and much more. It empowers developers to efficiently manage and customize PDF documents according to their specific requirements.

IronPDF not only excels in functionality but also offers the added benefit of being free for development purposes. This means that developers can leverage its capabilities without incurring any costs during the development phase of their projects. By utilizing IronPDF, developers can enhance their productivity and achieve remarkable results in their PDF-related tasks, ultimately delivering high-quality and efficient solutions within their .NET projects.

There are many other useful libraries such as IronPDF for working with PDF documents, IronXL for working with Excel documents, and IronOCR for working with OCR. Currently, you can get all five libraries for the price of just two by purchasing the complete Iron Suite. Visit our Iron Software Licensing Information for more details.

자주 묻는 질문

ASP.NET Core 웹 앱에서 PDF 파일을 표시하려면 어떻게 해야 하나요?

IronPDF 라이브러리를 사용하여 ASP.NET Core 웹 앱에서 PDF 파일을 표시할 수 있습니다. 먼저 NuGet 패키지 관리자를 통해 IronPDF 패키지를 설치한 다음, RenderRazorToPdf 또는 RenderHtmlAsPdf와 같은 메서드를 사용하여 Razor 페이지 또는 HTML 문자열을 표시용 PDF 문서로 변환합니다.

PDF 표시를 위해 ASP.NET Core 프로젝트를 설정하는 단계는 무엇인가요?

PDF 표시를 위한 ASP.NET Core 프로젝트를 설정하려면 Visual Studio를 설치하고, 새 ASP.NET Core 웹 앱 프로젝트를 만들고, NuGet을 통해 IronPDF 라이브러리를 추가하고, 애플리케이션 내에서 PDF 파일을 렌더링 및 표시하는 메서드를 사용하여 라이브러리를 통합합니다.

C#을 사용하여 HTML 문자열을 PDF로 변환하려면 어떻게 해야 하나요?

C#에서 HTML 문자열을 PDF로 변환하려면 IronPDF의 RenderHtmlAsPdf 메서드를 사용합니다. 이를 통해 HTML 콘텐츠를 PDF 문서로 렌더링하여 ASP.NET Core 애플리케이션에 표시할 수 있습니다.

ASP.NET Razor 페이지를 PDF로 변환할 수 있나요?

예, IronPDF를 사용하여 ASP.NET Razor 페이지를 PDF로 변환할 수 있습니다. 코드 비하인드 파일에 IronPDF 네임스페이스를 추가하고 RenderRazorToPdf 메서드를 사용하여 Razor 페이지를 PDF 문서로 렌더링하세요.

PDF 문서에 표지를 추가하려면 어떻게 해야 하나요?

추가 HTML 페이지 또는 파일을 PDF 문서의 첫 페이지로 렌더링한 다음 기본 PDF 콘텐츠와 병합하여 IronPDF를 사용하여 PDF 문서에 표지를 추가할 수 있습니다.

C#을 사용하여 여러 PDF 문서를 병합할 수 있나요?

예, IronPDF는 여러 PDF 문서를 병합하는 기능을 제공합니다. PdfDocument.Merge 메서드를 사용하여 여러 PDF를 하나의 문서로 결합할 수 있습니다.

PDF의 모든 페이지에 워터마크를 적용하려면 어떻게 해야 하나요?

PDF의 모든 페이지에 워터마크를 적용하려면 IronPDF의 WatermarkAllPages 메서드를 사용하세요. 이 방법을 사용하면 문서의 모든 페이지에 텍스트나 이미지를 워터마크로 오버레이할 수 있습니다.

.NET 개발자를 위해 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 웹 애플리케이션에서 PDF를 변환, 편집, 표시하는 등 PDF 조작을 위한 강력하고 유연한 라이브러리를 제공하므로 .NET 개발자에게 매우 유용합니다. 생산성을 향상시키고 워크플로를 간소화하여 개발자의 툴킷에서 유용한 도구가 될 수 있습니다.

C#에서 비밀번호로 PDF 문서를 보호하려면 어떻게 해야 하나요?

C#에서 비밀번호로 PDF 문서를 보호하려면 IronPDF를 사용하여 콘텐츠를 렌더링한 다음 저장하기 전에 PdfDocument 개체에 비밀번호를 설정하세요. 이렇게 하면 권한이 있는 사용자만 문서를 열 수 있습니다.

IronPDF는 .NET 10을 지원하며 .NET 10 프로젝트에서 어떻게 사용할 수 있나요?

예 - IronPDF는 .NET 10과 완벽하게 호환됩니다. 이 라이브러리는 .NET 10(.NET 9, 8, 7 등)을 지원하며 특별한 구성 없이 웹, 데스크톱, 콘솔 및 클라우드 환경에서 사용할 수 있습니다. 사용하려면 .NET 10 프로젝트에서 NuGet을 통해 IronPDF를 참조하고 평소와 같이 ChromePdfRenderer().RenderHtmlAsPdf(...)와 같은 메서드를 호출하기만 하면 됩니다.

IronPDF의 성능을 향상시키는 새로운 .NET 10 기능이 있나요?

예 - .NET 10에는 힙 할당 감소, 구조체 이스케이프 분석, 배열 인터페이스 메서드 가상화 등의 성능 향상 기능이 도입되어 런타임 효율성이 향상되었습니다. 특히 HTML-PDF 렌더링과 멀티스레드 또는 동시성이 높은 시나리오에서 이러한 개선 사항의 이점을 IronPDF에서 활용할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.