获取错误以生成pdf

时间:2013-04-09 07:54:06

标签: asp.net

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

    StringBuilder htmlText = new StringBuilder();
    htmlText.Append("<table style='color:red;' border='1'><tr><th>createing pdf</th><tr><td> abcdef</td></tr></table>");

    StringReader stringReader = new StringReader(htmlText.ToString());
    Document doc = new Document(PageSize.A4);
    List<iTextSharp.text.IElement> elements =
            iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(stringReader, null);
    doc.Open();
    foreach (object item in elements)
    {
        doc.Add((IElement)item);
    }
    doc.Close();
    // Response Output
    PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();

    //doc.Close();

    Response.Write("PDF is created");
}

}

我正在尝试创建pdf文件。但是当我打开它时,pdf只创建了0kb.Mean它的shw错误可能是pdf损坏了

1 个答案:

答案 0 :(得分:0)

我假设你正在使用iTextSharp库。

private void GeneratePDF()
    {
        try
        {
            string pdfPath = "~/PDF/File_1.pdf";
            StringBuilder sb = new StringBuilder();
            sb.Append("Name : chamara" + Environment.NewLine);
            sb.Append("Address : sri lanaka" + Environment.NewLine);
            sb.Append("Institute : SLIIT" + Environment.NewLine);
            Document doc = new Document();
            PdfWriter.GetInstance(doc, new FileStream(Server.MapPath(pdfPath), FileMode.Create));
            doc.Open();
            doc.Add(new Paragraph(sb.ToString()));
            doc.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }