THE LINUX FOUNDATION PROJECTS

Itextsharp Download Pdf C# Mvc Better Direct

The following example demonstrates creating a simple PDF with a heading and a paragraph.

Most real-world scenarios require tables (for invoices) or specific fonts. iTextSharp uses the PdfPTable class for layout. Adding a Styled Table itextsharp download pdf c# mvc

StringWriter sw = new StringWriter(); // Logic to render your MVC View to a string would go here string htmlContent = " Thank you for your business. "; using (StringReader sr = new StringReader(htmlContent)) { XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr); } Use code with caution. Best Practices for MVC Downloads The following example demonstrates creating a simple PDF

using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; using System.Web.Mvc; public class DocumentController : Controller { public ActionResult DownloadPdf() { // 1. Create a MemoryStream to hold the PDF data using (MemoryStream workStream = new MemoryStream()) { // 2. Initialize the Document and Writer Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f); PdfWriter writer = PdfWriter.GetInstance(document, workStream); // This ensures the stream stays open while we write to it writer.CloseStream = false; document.Open(); // 3. Add Content document.Add(new Paragraph("Hello World!")); document.Add(new Paragraph("Generated by iTextSharp in ASP.NET MVC.")); document.Close(); // 4. Reset stream position and return file byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return File(workStream, "application/pdf", "SampleDocument.pdf"); } } } Use code with caution. Advanced Formatting: Tables and Styling Adding a Styled Table StringWriter sw = new

In an MVC architecture, the logic for generating a PDF typically resides within a Controller action. We use the FileResult return type to send the binary data back to the browser.

Alternatively, use the Package Manager Console: Install-Package itextsharp Basic PDF Generation Logic