Friday 25 July 2014

MVC 4 - Creating PDF Files with iTextSharp

I've found in my latest job that just about every project requires spitting out PDFs in various flavours so here's a simple example:

// First things first, make sure you've got the package installed
// Package Manager
PM> Install-Package iTextSharp

// In your Controller make sure you reference iTextSharp.text and iTextSharp.pdf
using iTextSharp.text;
using iTextSharp.text.pdf;

// Outputs a Simple PDF with the Name and Description of a given Product
    public FileStreamResult ProductInfoPDF(int id)
        {
        Product = context.Products.Find(id);
// if we don't find anything then just quit
            if (Product == null)
            {
                return null;
            }

            MemoryStream workStream = new MemoryStream();
            Document document = new Document();
           // Landscape Layout
            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            PdfWriter.GetInstance(document, workStream).CloseStream = false;
            document.Open();
            // Heading
            Paragraph pHeading = new Paragraph("Product Information");
            pHeading.Alignment = Element.ALIGN_CENTER;
            pHeading.Font.SetStyle(Font.BOLD);
            pHeading.Font.Size = 12;
            pHeading.SpacingAfter = 18f;
            document.Add(new Paragraph(pHeading));                  
            Paragraph p = new Paragraph("Some background about this product.");
            p.Font.SetStyle(Font.BOLD);
            p.Font.Size = 8;
            document.Add(p);
            // Product Name
            Paragraph pProductName = new Paragraph("Product Name: " + Product.Name);
            pProductName.Font.SetStyle(Font.BOLD);
            pProductName.Font.Size = 8;
            document.Add(pProductName);
            // Description
            document.Add(new Paragraph("\n"));
            document.Add(new Paragraph("\n"));
            Paragraph pDescription = new Paragraph("Description");
            pEquip.Font.SetStyle(Font.BOLD);
            pEquip.Font.Size = 8;
            document.Add(pDescription );        
            document.Close();
            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;
            return new FileStreamResult(workStream, "application/pdf") { FileDownloadName = "Product_" + Product.Id.ToString() + ".pdf" };

        }


// Add  a link in your View
  @Html.ActionLink("Print", "ProductInfoPDF","Products" ,new { id = Model.Id }, new { @class = "printLink"})

No comments: