Tuesday, 16 October 2012

Generating PDF in Hindi

Generating PDF in Hindi using ITextSharp in asp.net

    First we have to download ItextSharp.dll and Fonts (hindi-devanagari-fonts.rar) from Internet, then install it in our system (select all fonts in that downloaded folder,right click on it, in that there is an option "install" ). Then write the code in .cs page

In .aspx:
 <asp:Button ID="btnpdf" runat="server" Text="GeneratePdf" OnClick="btnpdf_Click" />
In .cs page:

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.IO;
protected void btnpdf_Click(object sender, EventArgs e)
    {
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        string fileName = " EmployeeTranferReport.pdf";
        Response.AppendHeader("Content-Type", "application/pdf");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        stringWrite.WriteLine("<html><body encoding=" + BaseFont.IDENTITY_H + " style='font-family:Arial Unicode MS;font-size:12;'> <table style='width:100%'><tr><td align='center'><b>अगरतला नगरपालिका परिषद</b></td></tr><tr><td align='center'>अगरतला</td></tr></table> </body></html>");

        HtmlTextWriter hw = new HtmlTextWriter(stringWrite);
        StringReader sr = new StringReader(stringWrite.ToString());
        Document pdfDoc = new Document(PageSize.A4, 20f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter wi = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();

        string fontpath = Environment.GetFolderPath(Environment.SpecialFolder.Fonts) + "\\ARIALUNI.TTF";        //  "ARIALUNI.TTF" file copied from fonts folder and placed in the folder

        BaseFont bf = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        FontFactory.RegisterDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), true);
        FontFactory.Register(fontpath, "Arial Unicode MS");
        FontFactory.RegisterFamily("Arial Unicode MS", "Arial Unicode MS", fontpath);     
        htmlparser.Parse(sr);    
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
}

2 comments:

  1. error at line environment.specialfolder.fonts.
    error is :
    does not contain a defination for fonts ..
    rly .
    my email id is .. pawansaajnani@gmail.com

    ReplyDelete
  2. Please try to write all months name in Hindi. It will not work

    ReplyDelete