Skip to main content

Creating PDF in MVC 5 using ITextSharp

Creating PDF in MVC 5 using ITextSharp


For a long time I have been looking for free and cheaper ways of creating pdf documents within MVC. I have tried all the other options and none was able to give me the standard of document I wanted.

After long and tiresome nights of trying to figure out the solution I stumbled upon ItextSharp... This was my life changer. Maybe it might be for you too..


 Process


  1. Download ItextSharp using the Nuget Package manager and if you prefer using command line arguments you an use: Install-Package iTextSharp full documentation to this can be retrieved here
  2. Create a class that will be used to write the data you created as a byte array. How this works can be found here or here
     
      public class BinaryResult : ActionResult  
       {  
         private byte[] _fileBinary;  
         private string _contentType;  
         private string _fileName;  
         public BinaryResult(byte[] fileBinary, string contentType, string fileName)  
         {  
           _fileBinary = fileBinary; //gets the binary array to be written  
           _contentType = contentType; //gets the content type of the documet  
           _fileName = fileName; //gets the file name for the document  
         }  
         public override void ExecuteResult(ControllerContext context)  
         {  
           context.HttpContext.Response.Clear(); //clears the buffers  
           context.HttpContext.Response.ContentType = _contentType; // sets the content type for the document  
           context.HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + _fileName); //This allows the file to be downloadable  
           if (_fileBinary != null)  
           {  
             context.HttpContext.Response.BinaryWrite(_fileBinary); //returns dynamic made document for download  
           }  
         }  
       }  
     }  
    
  3. Format the document the way you want it. This can be achieved in many way but I used this blog here to accomplish this in  a different way.
      public ActionResult Pdf(List<Fee> fees)  
         {  
           var document = new Document(PageSize.A4, 50, 50, 25, 25);  
           // Create a new PdfWrite object, writing the output to a MemoryStream  
           var output = new MemoryStream();  
           var writer = PdfWriter.GetInstance(document, output); //setting an instance of the object to be written  
           // Open the Document for writing  
           document.Open();  
           // First, create our fonts... (For more on working w/fonts in iTextSharp, see: http://www.mikesdotnetting.com/Article/81/iTextSharp-Working-with-Fonts  
           var titleFont = FontFactory.GetFont("Arial", 14, Font.BOLD);  
           var subTitleFont = FontFactory.GetFont("Arial", 10, Font.BOLD);  
           var boldTableFont = FontFactory.GetFont("Arial", 10, Font.BOLD);  
           var endingMessageFont = FontFactory.GetFont("Arial", 10, Font.ITALIC);  
           var bodyFont = FontFactory.GetFont("Arial", 10, Font.NORMAL);  
           //Adding a pragraph to the document  
           document.Add(new Paragraph("Kilifi County Transaction", titleFont));  
           //adding a new ling after the paragraph   
           document.Add(Chunk.NEWLINE);  
           //Adding a paragraph to the document  
           document.Add(new Paragraph("Transaction Details", subTitleFont));  
           // Create the transaction details table - see http://www.mikesdotnetting.com/Article/86/iTextSharp-Introducing-Tables for more info  
           var orderInfoTable = new PdfPTable(new float[] { 0.8f, 1.0f, 1f, 1f, 0.7f, 0.7f, 1f, 1f, 1.2f });  
           orderInfoTable.WidthPercentage = 100; //make the table span the whole document  
           orderInfoTable.HorizontalAlignment = 1; //0 - left aligh, 1 - center, 2 - right align  
           orderInfoTable.SpacingBefore = 5; // spacing before cell  
           orderInfoTable.SpacingAfter = 5; // spaceing after cell  
           orderInfoTable.DefaultCell.Border =0; // used to add borders to the document  
           //Creating the headers to the that tables  
           orderInfoTable.AddCell(new Phrase("Reciept No:", boldTableFont));  
           // orderInfoTable.AddCell(new Phrase("Attendant", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Terminal", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Location", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Tarrif", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Rate (KSH)", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Units/ Weight", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Reg No.", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Amount", boldTableFont));  
           orderInfoTable.AddCell(new Phrase("Timestamp", boldTableFont));  
           //lopping through the list to populate the table with data  
           foreach (var feeItem in fees)  
           {  
             orderInfoTable.AddCell(new Phrase(feeItem.ID.ToString(), bodyFont));  
           //   orderInfoTable.AddCell(new Phrase(feeItem.Attendant.FullNames, bodyFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.Terminal.Name, bodyFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.Location.Name, bodyFont));// Phrase("Location", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.Tarrif.Name, bodyFont));// Phrase("Tarrif", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.Tarrif.Amount.ToString(), bodyFont)); // Phrase("Rate (KSH)", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(String.Format("{0:0.00}", (feeItem.Amount / feeItem.Tarrif.Amount)), bodyFont));// Phrase("Unit/Weight", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.RegistrationNumber, bodyFont));// Phrase("Reg No.", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(String.Format("{0:0}", feeItem.Amount), bodyFont));// Phrase("AMount", boldTableFont));  
             orderInfoTable.AddCell(new Phrase(feeItem.Timestamp.ToString(), bodyFont));// Phrase("Timestamp", boldTableFont));  
           }  
           //adding all the content to the document object or else nothing will display  
           document.Add(orderInfoTable);  
           // Add ending message  
           var visionMessage = new Paragraph(" Vision: \"To be a leading, vibrant, highly productive, secure and prosperous county providing a high quality of life for all its inhabitants.\"" , endingMessageFont);  
           visionMessage.Alignment = 1;  
           document.Add(visionMessage);  
           var misionMessage = new Paragraph(" Vision: \"The county will provide the environment for efficient utilization of resources, effective provision of essential services, and industrial growth and development initiatives for improved quality of life for all.\"", endingMessageFont);  
           misionMessage.Alignment = 1;  
           document.Add(misionMessage);  
           // Finally, add an image in the upper right corner  
           //var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/4guysfromrolla.gif"));  
           //logo.SetAbsolutePosition(440, 800);  
           //document.Add(logo);  
           document.Close();  
           //creating the output dynamically  
           return new BinaryResult(output.ToArray(), "application/pdf", "Trascation.pdf");  
         }  
    
  4. Finally I call the method within my Action whenever I want to export the content to a pdf
      }  
           else if (command == "Export")  
           {  
             return Pdf(fees);  
           }  
       
This were were my simple steps to getting a document exported to pdf within mvc.
For more reading on creating and formatting the document according to your preference you can go here. Mike has done a good job explaining how this can be achieved.




Comments

Popular posts from this blog

Installing libssl1.0 on Ubuntu 22.04

Following the upgrade of distro from 20.04 to 22.04 the libssl packages got affected, this ended up causing my vpn client to fail. The client kept opening and closing immediately.  on futher investigation I found the issue as the libssl client. Attached is a screenshot of the message I was getting when I tries starting it from the terminal. Tring to install libsll1.0-dev from apt was generating the following error: Due to this installing the package was not viable via the regular way, I really didn't want to downgrade back to 20.04 as this could have meant a clean installation, and I had just come from doing that, as the upgrade wasn't successful, but I still needed to try out the new 22.04 features. Google been my best friend finally come through after a long search on how to install libssl1.0-dev. I ended up landing on this link  , here they gave some instruction on how to install libss1.0-dev. Below are the steps of installing libssl1.0-dev on ubuntu 22.04 for backward compa

Converting DateTime C# to DateTime.UTC javascript

Here is a simple way to change a C# datetime to a javascript Datetime.UTC value that can be used in the highcharts pointstart field. In C# private double DateUTCDate(DateTime date) { return date.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds } This will return a value that can be used directly in javascript series: { pointStart: dataFromCsharp, pointInterval: 3600 * 1000 // one day } highcharts pointstart only used Date.UTC values if you are timestamp for the x-axis