从ASP.NET C#中的数据源导出为PDF

时间:2019-03-06 11:21:42

标签: c# asp.net

我正在尝试在asp.net中实现“导出为PDF”模块。没有错误,没有例外,但仍然无法生成PDF文档。尝试过从stackoverflow解决方案,但没有帮助。 这是我的代码示例...  还在<%@ page>标记

中应用了EnableEventValidation =“ false”
 <asp:Button ID="btnExportTOPDF" Text="Export to PDF" runat="server" Style="color: white" CssClass="form-control btn-danger rcolr"
    OnClick="btnExportTOPDF_Click" /> 


    //Code Behind
    public DataTable bindUserData()
        {
            DataTable DtUser = new DataTable();
            SqlDataAdapter adapter = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand("bindUSermaster", con);
            cmd.CommandType = CommandType.StoredProcedure;

            adapter.SelectCommand = cmd;
            adapter.Fill(DtUser);
            gvuser.DataSource = DtUser;
            gvuser.DataBind();

            return DtUser;
        }


     protected void btnExportTOPDF_Click(object sender, EventArgs e)
        {
            ExportBindPDF();
        }

     public void ExportBindPDF()
        {
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        //To Export all pages
                        gvuser.AllowPaging = false;
                        this.bindUserData();

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

                        Response.ContentType = "application/pdf";
                        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.Write(pdfDoc);
                        //Response.End();
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

        }

请帮助。

0 个答案:

没有答案