How To Generate And ((free)) Download Pdf Report From Database In Mvc Using Itextsharp C# 【Proven — Secrets】

using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using System.Web.Mvc; using System.Collections.Generic; using System.Linq; public class ReportController : Controller { public ActionResult DownloadPDF() { // 1. Fetch data from Database List allProducts = new List (); using (var db = new MyDatabaseContext()) { allProducts = db.Products.ToList(); } // 2. Setup PDF document Document pdfDoc = new Document(PageSize.A4, 25, 25, 25, 25); MemoryStream workStream = new MemoryStream(); PdfWriter.GetInstance(pdfDoc, workStream).CloseStream = false; pdfDoc.Open(); // 3. Add Content - Title Paragraph title = new Paragraph("Inventory Report", FontFactory.GetFont("Arial", 18, Font.BOLD)); title.Alignment = Element.ALIGN_CENTER; pdfDoc.Add(title); pdfDoc.Add(new Chunk("\n")); // Add spacing // 4. Create and Style Table PdfPTable table = new PdfPTable(3); // 3 Columns table.WidthPercentage = 100; // Add Headers table.AddCell(new PdfPCell(new Phrase("Product Name", FontFactory.GetFont("Arial", 12, Font.BOLD)))); table.AddCell(new PdfPCell(new Phrase("Price", FontFactory.GetFont("Arial", 12, Font.BOLD)))); table.AddCell(new PdfPCell(new Phrase("Stock", FontFactory.GetFont("Arial", 12, Font.BOLD)))); // 5. Populate Table with Data foreach (var item in allProducts) { table.AddCell(item.Name); table.AddCell(item.Price.ToString("C")); table.AddCell(item.Stock.ToString()); } pdfDoc.Add(table); pdfDoc.Close(); // 6. Return File for Download byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return File(workStream, "application/pdf", "ProductReport.pdf"); } } Use code with caution. Step 4: Add the Download Link in the View

A database table populated with data (we will use a "Products" table for this example). Step 1: Install iTextSharp using iTextSharp

This guide walks you through the entire process of fetching data from a SQL database and rendering it into a professional PDF document for the user to download. Prerequisites Add Content - Title Paragraph title = new

📍 : This represents the PDF page itself. You can define size (A4, Letter) and margins here. Return File for Download byte[] byteInfo = workStream

Before we dive into the code, ensure you have the following: Visual Studio (2019 or later recommended). A basic understanding of ASP.NET MVC and C#.

The easiest way to add iTextSharp to your project is via the NuGet Package Manager. Right-click your project in Solution Explorer. Select . Search for iTextSharp and click Install .

📍 : We use this to hold the PDF data in memory before serving it to the user. This avoids the need to save a physical file on the server's hard drive, which is better for performance and security.