using System.IO; using System.Web.Mvc; using PdfSharp.Pdf; using PdfSharp.Drawing; public class HomeController : Controller { [HttpGet] public ActionResult DownloadPdf() { // 1. Create a new PDF document PdfDocument document = new PdfDocument(); document.Info.Title = "Created with PDFsharp"; // 2. Create an empty page PdfPage page = document.AddPage(); // 3. Get an XGraphics object for drawing XGraphics gfx = XGraphics.FromPdfPage(page); // 4. Draw content (Text, Shapes, etc.) XFont font = new XFont("Verdana", 20, XFontStyle.Bold); gfx.DrawString("Hello, ASP.NET MVC!", font, XBrushes.Black, new XRect(0, 0, page.Width, page.Height), XStringFormats.Center); // 5. Save the document to a MemoryStream using (MemoryStream stream = new MemoryStream()) { document.Save(stream, false); byte[] fileContents = stream.ToArray(); // 6. Return the file for download return File(fileContents, "application/pdf", "MyGeneratedReport.pdf"); } } } Use code with caution. 3. Trigger the Download from the View
Currently the most popular "code-first" library. It uses a modern fluent API similar to Compose or SwiftUI to build complex layouts with automatic pagination.
The industry heavyweight for deep PDF manipulation, digital signatures, and encryption. Note that it uses an AGPL/Commercial license. create a pdf file and download using asp.net mvc
This example uses a standard programmatic approach (similar to ) to generate a file in memory and return it to the user's browser. 1. Install the Library
Generating PDF documents in ASP.NET MVC is a common requirement for creating invoices, reports, and digital certificates. While the .NET Framework does not have a native "Save as PDF" function for web views, several powerful libraries—both open-source and commercial—allow you to bridge this gap. Choosing the Right PDF Library for 2025/2026 using System
In your HomeController.cs , create a method that generates the PDF and returns a FileResult . This ensures the file is streamed directly to the user for download rather than being saved on the server's hard drive.
Best for "pixel-perfect" HTML-to-PDF conversion using a Chromium rendering engine. It is highly recommended for developers who want to turn their existing Razor views into PDFs without redesigning them. Get an XGraphics object for drawing XGraphics gfx
Depending on your project needs, you should choose a library based on whether you prefer writing C# code to "draw" the PDF or converting existing HTML/CSS views.