Sunday 9 October 2016

PDF File creation in ASP.NET using itextsharp

This code snippet describes how to generate a pdf file in asp.net C#. To create a file we are using "itextsharp.dll". You can download it from the download link as follows. Just put it in your bin folder and take an overview of code given below. 

using iTextSharp.text;  
using iTextSharp.text.pdf;  
public partial class _Default: Page {  
    protected void Page_Load(object sender, EventArgs e) {}  
    protected void GenerateReport_Click(object sender, EventArgs e) {  
        var doc = new Document(PageSize.A4); // defining the docment  
        var output = new MemoryStream();  
        var wri = PdfWriter.GetInstance(doc, output);  
        var fpara = new Phrase("\n");  
        fpara.Add(" * * * * * * You are Welcome * * * * * * ");  
        fpara.Add(" \n");  
        fpara.Add(" \n");  
        string url = "~/Image/kbs.jpg";  
        var headerImage = iTextSharp.text.Image.GetInstance(new Uri(Server.MapPath(url)));  
        /// Adding border to image if required  
        headerImage.Border = iTextSharp.text.Rectangle.BOX;  
        headerImage.BorderColor = iTextSharp.text.Color.BLACK;  
        headerImage.BorderWidth = 3 f;  
        Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        doc.Open();  
        Rectangle defaultPageSize = PageSize.A4;  
        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, 
           BaseFont.CP1252, false);  
        Font fontH1 = new Font(bfTimes, 9, Font.NORMAL, Color.BLUE);  
        PdfPTable table = new PdfPTable(1);  
        // You can change the number of columns as per required in our case i think we need 
       //only one column  
        List < string > paras = new List < string > ();  
        foreach(string p1 in paras) {  
            PdfPCell cell = new PdfPCell(new Phrase(p1, fontH1));  
            //cell.FixedHeight = 15f;  
            table.AddCell(cell);  
        }  
        doc.Add(headerImage);  
        /// added header image  
        fpara.Add("visit us : kumarbhimsenbgp.blogspot.in");  
        fpara.Add("\n");  
        doc.Add(fpara); /// added 1  
        doc.Add(table); /// added table  
        doc.NewPage(); /// aad a new Page when doc item exceed.  
        doc.Close(); //Close document  
        Response.ContentType = "application/pdf";  
        Response.AddHeader("content-disposition", "attachment;filename=KbsTest.pdf");  
        Response.BinaryWrite(output.ToArray());  
    }  

}  

No comments:

Post a Comment