使用Itextsharp将转发器数据转换为asp.net中的pdf

时间:2014-07-23 12:35:13

标签: asp.net itextsharp

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

protected void btnExport_Click(object sender, EventArgs e)
{
    try
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=FileName.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        rptUserList.DataBind();
        rptUserList.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);
        //htmlparser.Parse(new StringReader("hello world"));
        pdfDoc.Close();

        Response.Write(pdfDoc);
        Response.End();
    }
    catch (Exception ex)
    {
        throw new Exception("btnExport_Click Error : " + ex.Message);
    }

我得到的文件没有页面。请帮忙。

1 个答案:

答案 0 :(得分:0)

你应该使用  this.rptUserList.RenderControl(hw); 而不是rptUserList.RenderControl(hw);