🧾 How to Download a PDF File in a Razor View and Retrieve File Properties (If Needed)

How to Download a PDF File in a Razor View and Retrieve File Properties if Needed

🧠 Introduction

While working with ASP.NET Core MVC applications, you may sometimes need to handle PDF files dynamically.

For instance, you might have to download a PDF from a remote server and display its properties — such as file size and page count — directly in your Razor view.

Although this isn’t the most performance-efficient method, there are real-world scenarios where you must calculate such properties on the fly within the view.

In this guide, you’ll learn how to:

  • Download a PDF file from a URL within a Razor view
  • Retrieve its properties such as file size and number of pages
  • Optionally use IronPDF for a more powerful implementation

āš™ļø The Problem

Typically, file-related properties (like file size, extension, or page count) are calculated and stored when a file is uploaded to a CMS or storage service.

This ensures efficiency, since you don’t have to re-process files on every request.

However, sometimes:

  • These properties are not stored in your database, or
  • You’re dealing with externally hosted files (like on Amazon S3)

In such cases, you may need to calculate PDF properties dynamically in your Razor view.

šŸ’” The Solution

Here’s how to handle this step-by-step in Razor.

This example assumes you’re working with a PDF file hosted locally or on a remote server (like AWS S3) and you need to download it, get its file size, and count its pages.

@{
// Initialize the result string with a default value
string result = "0 " + await localizationService.T("filesize.kb", Model.Language.Id);
string fileUrl = "";
string fileExtension = "";
// Check if the file path or URL exists
if (!string.IsNullOrEmpty(articleModel.FilePath))
{
try
{
// Retrieve the host information from the request headers
string hostHeader = Context.Request.Headers["host"];
fileUrl = string.Format("{0}://{1}", Context.Request.Scheme, hostHeader);
// Check if the file is hosted locally or on a remote server (e.g., AWS)
if (!articleModel.FilePath.Contains("remoteserver.com/"))
{
fileUrl = fileUrl + articleModel.FilePath;
}
else
{
fileUrl = articleModel.FilePath; // Use the full URL if already provided
}
// Get the file extension (e.g., pdf)
fileExtension = System.IO.Path.GetExtension(fileUrl);
if (!string.IsNullOrEmpty(fileExtension))
{
fileExtension = fileExtension.Substring(1); // Remove the leading dot
}
// Initialize memory stream and set up HttpClient for file download
var memoryStream = new MemoryStream();
var httpClient = new HttpClient();
var userAgent = new ProductInfoHeaderValue("exampleApp", "1.0");
httpClient.DefaultRequestHeaders.UserAgent.Add(userAgent);
// Download the file from the URL
var fileData = await httpClient.GetByteArrayAsync(fileUrl);
// Load the file data into a memory stream
var fileContentStream = new MemoryStream(fileData);
memoryStream = fileContentStream;
memoryStream.Position = 0;
// Use a PDF reader library to extract file properties (dummy library assumed)
PdfReader dummyPdfReader = new PdfReader(memoryStream);
int pageCount = dummyPdfReader.NumberOfPages;
decimal fileSizeInBytes = dummyPdfReader.FileLength;
// Convert the file size to a human-readable format (e.g., KB, MB, GB)
string[] sizeUnits = { "B", "KB", "MB", "GB" };
int sizeOrder = 0;
while (fileSizeInBytes >= 1024 && sizeOrder + 1 < sizeUnits.Length)
{
sizeOrder++;
fileSizeInBytes = fileSizeInBytes / 1024;
}
// Format the result string with file size and number of pages
result = String.Format("{0:0.##} {1}, {2}", fileSizeInBytes, sizeUnits[sizeOrder], pageCount + " Pages");
}
catch (Exception ex)
{
// In case of error, default back to "0 KB"
result = "0 " + await localizationService.T("filesize.kb", Model.Language.Id);
}
}
}

šŸ“˜ Code Explanation:
This Razor block downloads a PDF file, extracts its basic metadata, and formats the result for display in the view.

🧩 Explanation of the Code

1. Checking for a File:
Verifies that the file path (File1) is not null or empty.

2. Building the URL:
If the file is local, it constructs the base URL; otherwise, it uses the full remote URL (like an S3 link).

3. Extracting File Extension:
Extracts the .pdf extension for validation or conditional logic.

4. Downloading the File:
Uses HttpClient to fetch the file bytes with a custom User-Agent.

5. Reading PDF Properties:
Loads the file into a MemoryStream and reads the number of pages and file size using a PDF library.

šŸš€ A Concrete Implementation with IronPDF

If you’re looking for a production-ready library to replace the dummy reader above, IronPDF is an excellent choice.

It not only lets you read PDF properties, but also convert Razor views or HTML to PDF in C# — a perfect fit for .NET web applications.

šŸ”§ Example: Reading PDF Properties with IronPDF

// Using IronPDF to read PDF properties
// Install-Package IronPdf
using IronPdf;
var pdfDocument = PdfDocument.FromStream(memoryStream);
int pageCount = pdfDocument.PageCount;
decimal fileSizeInBytes = memoryStream.Length;

šŸ’” Bonus: Convert Razor View to PDF

// Convert Razor or HTML to PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(razorHtml);
byte[] pdfBytes = pdf.BinaryData;

With IronPDF, you get two capabilities in one library:

  • šŸ“– Reading and analyzing existing PDFs
  • 🧱 Generating new PDFs directly from your Razor views

It uses Chrome’s rendering engine, so your CSS, JavaScript, and layout render exactly as they do in the browser.

And if you work across different stacks — IronPDF now supports .NET, Java, Python, and Node.js as well.

āš–ļø Calculating File Size

Once the PDF is read, you can convert its raw byte length into a human-friendly format (KB, MB, or GB).

This helps display meaningful file info to users, e.g.,
"1.23 MB, 10 Pages" instead of "1294960 bytes".

šŸ Conclusion

While the above code demonstrates how to dynamically download a PDF file and retrieve its properties within a Razor view, it’s worth noting that this approach is not ideal for high-performance scenarios.

In most cases, file properties (size, type, and page count) should be calculated at upload time and stored in the database. This ensures faster retrieval and avoids repeatedly reading large files on every request.

However, if:

  • The files are externally hosted, or
  • The properties aren’t stored anywhere

…then this method can be incredibly useful for on-demand metadata extraction.

Use it wisely, and you’ll have a flexible way to inspect and even generate PDFs directly from your ASP.NET Core application.

Happy coding! šŸ’»

If you found this blog helpful, don’t forget to give a like.

Buy me a coffee

Learn more 🧾 How to Download a PDF File in a Razor View and Retrieve File Properties (If Needed)

Leave a Reply