Skip to footer content
USING IRONPDF

How to Upload and Download PDF Files in ASP .NET C# with IronPDF

Managing PDF Download Files and uploads is a common requirement in ASP.NET Core MVC (Model-View-Controller) web applications. Whether storing documents in a database table using EF Core or processing them server-side before saving, developers need reliable methods to handle PDF documents efficiently.

This article demonstrates how to upload and download PDF file in ASP .NET C# while leveraging IronPDF to add watermarks, generate documents on-demand, and integrate seamlessly with .NET Core projects.

How Do You Create a Database Table for PDF Storage?

The first step involves creating a database table to store uploaded PDF files as binary data. The following code shows a model class representing the file structure with properties for the file name, content type, and byte array storage. This is a common pattern in New Tutorials involving file persistence in EF Core.

public class PdfFileModel
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public byte[] FileData { get; set; }
    public DateTime UploadedDate { get; set; }
}
public class PdfFileModel
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }
    public byte[] FileData { get; set; }
    public DateTime UploadedDate { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This model maps directly to a database table where FileData stores the PDF document as a varbinary column. The FileName property preserves the original file name, while ContentType ensures proper content disposition when serving the download PDF file to users. You may also add Details columns or metadata fields depending on your requirements.

How Can You Upload PDF Files to a Database in ASP.NET Core?

To upload one or more files, create a controller action that accepts an IFormFile parameter. The FileUpload Control in your HTML form must use enctype="multipart/form-data" to properly Load the uploaded file to the server and ensure the PDF bytes are transmitted correctly. Note that your namespace will be the same as your project name.

namespace UploadPdfs.Controllers
{
public class PdfController : Controller
{
    private readonly ApplicationDbContext _context;
    public PdfController(ApplicationDbContext context)
    {
        _context = context;
    }
    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No file selected");
        using (var stream = new MemoryStream())
        {
            await file.CopyToAsync(stream);
            var pdfFile = new PdfFileModel
            {
                FileName = file.FileName,
                ContentType = file.ContentType,
                FileData = stream.ToArray(),
                UploadedDate = DateTime.Now
            };
            _context.PdfFiles.Add(pdfFile);
            await _context.SaveChangesAsync();
        }
        return RedirectToAction("Index");
    }
}
}
namespace UploadPdfs.Controllers
{
public class PdfController : Controller
{
    private readonly ApplicationDbContext _context;
    public PdfController(ApplicationDbContext context)
    {
        _context = context;
    }
    [HttpPost]
    public async Task<IActionResult> Upload(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No file selected");
        using (var stream = new MemoryStream())
        {
            await file.CopyToAsync(stream);
            var pdfFile = new PdfFileModel
            {
                FileName = file.FileName,
                ContentType = file.ContentType,
                FileData = stream.ToArray(),
                UploadedDate = DateTime.Now
            };
            _context.PdfFiles.Add(pdfFile);
            await _context.SaveChangesAsync();
        }
        return RedirectToAction("Index");
    }
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Uploading a Simple File

How to Upload and Download PDF Files in ASP .NET C# with IronPDF: Image 1 - UI showing the uploaded PDF

Here, the IFormFile interface provides access to the uploaded file's stream. You can Right-Click your project in Solution Explorer and choose Add → New Folder to organize uploaded files if you prefer file system storage instead of a database.

Use the following form to trigger uploads:

<form method="post" action="/Pdf/Upload" enctype="multipart/form-data">
    <button type="submit">Upload</button>
</form>
<form method="post" action="/Pdf/Upload" enctype="multipart/form-data">
    <button type="submit">Upload</button>
</form>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How Do You Process Uploaded PDF Files with Watermarks?

Before saving uploaded PDF files to the database, you can process them using IronPDF's watermarking features. This allows adding branding, "DRAFT" labels, or "CONFIDENTIAL" stamps to every PDF document that enters your system.

[HttpPost]
 public async Task<IActionResult> UploadWithWatermark(IFormFile file)
 {
     if (file == null || file.Length == 0)
         return BadRequest("No file selected");
     // 1. Read the uploaded file into a byte array
     using (var stream = new MemoryStream())
     {
         await file.CopyToAsync(stream);
         byte[] fileBytes = stream.ToArray();
         // 2. Process with IronPDF (Apply Watermark)
         var PDF = new IronPdf.PdfDocument(fileBytes);
         pdf.ApplyWatermark("<h2 style='color:red'>CONFIDENTIAL</h2>", 60, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
         // 3. Define the new file name and path
         string uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
         string filePath = Path.Combine(_storagePath, uniqueFileName);
         // 4. Save the processed bytes to the file system
         System.IO.File.WriteAllBytes(filePath, pdf.BinaryData);
         // 5. Save metadata to the in-memory list (instead of DB)
         var pdfFile = new PdfFileModel
         {
             Id = _nextId++,
             FileName = file.FileName,
             ContentType = "application/pdf",
             FilePath = filePath, // Store the physical path
             UploadedDate = DateTime.Now
         };
         _pdfFiles.Add(pdfFile);
     }
     return RedirectToAction("Index");
 }
[HttpPost]
 public async Task<IActionResult> UploadWithWatermark(IFormFile file)
 {
     if (file == null || file.Length == 0)
         return BadRequest("No file selected");
     // 1. Read the uploaded file into a byte array
     using (var stream = new MemoryStream())
     {
         await file.CopyToAsync(stream);
         byte[] fileBytes = stream.ToArray();
         // 2. Process with IronPDF (Apply Watermark)
         var PDF = new IronPdf.PdfDocument(fileBytes);
         pdf.ApplyWatermark("<h2 style='color:red'>CONFIDENTIAL</h2>", 60, IronPdf.Editing.VerticalAlignment.Middle, IronPdf.Editing.HorizontalAlignment.Center);
         // 3. Define the new file name and path
         string uniqueFileName = Guid.NewGuid().ToString() + "_" + file.FileName;
         string filePath = Path.Combine(_storagePath, uniqueFileName);
         // 4. Save the processed bytes to the file system
         System.IO.File.WriteAllBytes(filePath, pdf.BinaryData);
         // 5. Save metadata to the in-memory list (instead of DB)
         var pdfFile = new PdfFileModel
         {
             Id = _nextId++,
             FileName = file.FileName,
             ContentType = "application/pdf",
             FilePath = filePath, // Store the physical path
             UploadedDate = DateTime.Now
         };
         _pdfFiles.Add(pdfFile);
     }
     return RedirectToAction("Index");
 }
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Watermarked PDF

How to Upload and Download PDF Files in ASP .NET C# with IronPDF: Image 2 - PDF watermarked and then saved to our database

IronPDF’s ApplyWatermark method supports HTML content, opacity, rotation, and alignment. This is also helpful when generating reports triggered by HTTP requests or automated worker tasks. Explore additional PDF editing capabilities for headers, footers, and page manipulation.

How Can You Download Files from the Database?

To download PDF files stored in your database, create an action that retrieves the byte array and returns it as a FileResult. The following code demonstrates the complete download functionality:

public IActionResult Download(int id)
{
    var pdfFile = _pdfFiles.FirstOrDefault(f => f.Id == id);
    if (pdfFile == null || !System.IO.File.Exists(pdfFile.FilePath))
        return NotFound();
    byte[] fileBytes = System.IO.File.ReadAllBytes(pdfFile.FilePath);
    return File(fileBytes, pdfFile.ContentType, pdfFile.FileName);
}
public IActionResult Download(int id)
{
    var pdfFile = _pdfFiles.FirstOrDefault(f => f.Id == id);
    if (pdfFile == null || !System.IO.File.Exists(pdfFile.FilePath))
        return NotFound();
    byte[] fileBytes = System.IO.File.ReadAllBytes(pdfFile.FilePath);
    return File(fileBytes, pdfFile.ContentType, pdfFile.FileName);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Stored PDF Files with Download Buttons

How to Upload and Download PDF Files in ASP .NET C# with IronPDF: Image 3 - List of stored PDF files

When displaying download buttons, you can Search entries, show Details, and output results based on a Query or filter.

The File method returns the byte array with the appropriate content type and file name. This triggers a download in the user's browser with proper content disposition headers. Display a download button in your view using HTML helpers:

<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FileName</td>
            <td>@item.UploadedDate</td>
            <td>
                <a href="/Pdf/Download/@item.Id">Download</a>
            </td>
        </tr>
    }
</table>
<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.FileName</td>
            <td>@item.UploadedDate</td>
            <td>
                <a href="/Pdf/Download/@item.Id">Download</a>
            </td>
        </tr>
    }
</table>
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For file system storage as an alternative to database storage, save files to a server path and store only the file path in your database table.

How Do You Create and Download PDF Documents On-Demand?

Beyond storing existing files, you can generate new PDF documents dynamically using IronPDF's HTML-to-PDF conversion. This approach enables creating reports, invoices, or certificates on-demand:

public IActionResult GeneratePdf()
{
    var renderer = new IronPdf.ChromePdfRenderer();
    var PDF = renderer.RenderHtmlAsPdf("<h1>Generated Report</h1><p>Created: " + DateTime.Now + "</p>");
    return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
public IActionResult GeneratePdf()
{
    var renderer = new IronPdf.ChromePdfRenderer();
    var PDF = renderer.RenderHtmlAsPdf("<h1>Generated Report</h1><p>Created: " + DateTime.Now + "</p>");
    return File(pdf.BinaryData, "application/pdf", "report.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

PDF Generated On-Demand

How to Upload and Download PDF Files in ASP .NET C# with IronPDF: Image 4 - Generated example PDF

The ChromePdfRenderer class converts HTML strings into pixel-perfect PDF documents, supporting CSS styling and JavaScript execution. This method returns the generated PDF file directly to the browser for download without intermediate storage. This method requires no Default storage and is triggered instantly via HTTP GET.

Start your free trial to explore IronPDF's full capabilities for ASP.NET Core PDF handling, including merging documents, form filling, and digital signatures.

Conclusion

Implementing PDF upload and download functionality in ASP.NET Core combines standard file-handling techniques with IronPDF’s advanced processing capabilities. With the ability to watermark, generate, store, and serve PDF files, your application becomes more robust and user-friendly.

You can integrate further features such as merging documents, adding metadata, filling forms, or generating interactive content. Review IronPDF’s reference documentation or browse new tutorials in our blog for advanced capabilities. Have any following error issues with your code? Check out the helpful troubleshooting guides.

Ready to enhance your ASP.NET Core application with advanced PDF features? Purchase an IronPDF license for production deployment, visit the extensive documentations for additional information, or chat with our team for guidance on your specific project requirements.

Frequently Asked Questions

How can I upload PDF files in an ASP.NET Core MVC application?

To upload PDF files in an ASP.NET Core MVC application, you can use the IFormFile interface to capture file data from a form and then process it server-side before saving, possibly with the help of IronPDF for further PDF manipulation.

What is the best way to download PDF files in ASP.NET?

The best way to download PDF files in ASP.NET is to use the FileResult action in your controller. IronPDF can assist in generating and modifying PDFs server-side to ensure they are ready for download.

Can I store PDF files in a database using ASP.NET?

Yes, you can store PDF files in a database using ASP.NET by converting the file to a byte array and saving it as a binary large object (BLOB). IronPDF can help in processing the PDF before storage.

How does IronPDF help with watermarking PDFs in ASP.NET?

IronPDF provides functionality to easily add text or image watermarks to PDFs, which can be integrated into your ASP.NET application to modify documents before download or storage.

What are the advantages of using EF Core for PDF storage?

EF Core allows for efficient object-relational mapping, making it easier to manage PDF storage and retrieval in a structured and scalable manner within your ASP.NET application.

Is it possible to manipulate PDF content in ASP.NET applications?

Yes, with IronPDF, you can manipulate PDF content, including editing text, images, and metadata, which can be useful for customizing documents before they are served to users.

How can I handle file uploads securely in ASP.NET?

To handle file uploads securely in ASP.NET, you should validate file types, limit file sizes, and store them in secure locations. Using libraries like IronPDF can also help ensure the integrity of the PDF files themselves.

What are common challenges when working with PDFs in web applications?

Common challenges include ensuring file compatibility, managing large file sizes, and maintaining document integrity. IronPDF helps overcome these by providing robust tools for PDF creation and manipulation.

Can I convert different file types to PDF in ASP.NET?

Yes, IronPDF allows you to convert various file types, such as HTML or image files, into PDFs seamlessly within your ASP.NET application.

What is the role of Model-View-Controller (MVC) in handling PDFs in ASP.NET?

The MVC pattern helps in organizing the code for handling PDFs by separating data handling (Model), user interface (View), and application logic (Controller), making it easier to manage and extend PDF functionalities.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More