Thursday 20 September 2012

Export To PDF in sharepoint 2010/C#

I had an requirement to export some data to PDF format in Sharepoint application pages.

First You have to download and attach a DLL from ItextSharp.dll .(Can be downloaded from Here).Add it into  your webpart or solution  or for application pages.

For application pages and for inline coding add following  lines


<%@ Register TagPrefix="itext" Namespace="iTextSharp.text" Assembly="itextsharp, Version=5.3.0.0, Culture=neutral, PublicKeyToken=8354ae6d2174ddca" %>
<%@ Import Namespace="iTextSharp.text.pdf" %>
<%@ Import Namespace="iTextSharp.text.html.simpleparser" %>


For coding purpose add following lines


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;


Then add the following  code to export to PDF


private DataTable  SearchItem()
    {
        DataTable dt = new DataTable();
        SPSecurity.RunWithElevatedPrivileges(delegate
        {
            SPList list = SPContext.Current.Web.Lists["TestList"];
         
       
            string query = null;
            SPQuery qry = new SPQuery(list.DefaultView);
            //SPListItemCollection lstColl =
            int iCnt = 0;
            try
            {

                qry.ViewFields = "<FieldRef Name='LinkTitleNoMenu' /><FieldRef Name='TestColumn' />";
                    qry.Query = query;
                 
                dt= list.GetItems(qry).GetDataTable();
                 

                 
                }

            catch (Exception ex) { Response.Write(ex.Message); }
        });
        return dt;
    }
    protected void btnExport_click(object sender, EventArgs e)
    {
        DataTable dt1 = SearchItem();
     

        //Get the data from database into datatable

        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt1;
        GridView1.DataBind();


        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition",
          "attachment;filename=DataTable.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
 

  public override void VerifyRenderingInServerForm(Control control)
    {
    }


If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we setVerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.



After the button Click the PDf file will ask you to save or open the File.After that you can't do any post back options in that page.for doing such you have to add a little bit of code into that page within a script block.
Add the following code to that particular page



   <script type="text/javascript">

            _spOriginalFormAction = document.forms[0].action;

            _spSuppressFormOnSubmitWrapper = true;

</script>



Happy Coding  :)





12 comments:

  1. Thanks a lot. It was helpful.

    ReplyDelete
  2. Thanks a ton! However I have 1 query, I want to hide the "ID", "Created" and "Modified" column in the pdf. How to do that?
    Please let me know! Your answer will be of much help to me....

    ReplyDelete
  3. Just add columns to data table with "ID", "Created" and "Modified" then bind the data table

    ReplyDelete
  4. Awesome! By any chance can this code be modified to export a single item to PDF??

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. this post is useful for me but HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    am getting error in this page

    ReplyDelete
  7. Hi RatiKanta , i had successfully completed my task by using this Code thanks for you great help. but is their any possibility to archive same functionary with out using this dll. Can you please suggest me if it their in share point

    Thanks & Regards,
    Sunitha.

    ReplyDelete
    Replies
    1. Thanks !!!
      From my knowledge "NO"

      Delete
    2. Ok thanks for Your Quick reply's no problem am using these open source dlls only.

      Delete