【问题标题】:Getting error to generate pdf生成pdf时出错
【发布时间】:2013-04-09 07:54:06
【问题描述】:
 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。意味着当我打开它时它的 shw 错误可能是 pdf 损坏

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    我假设您正在使用 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;
            }
        }
    

    【讨论】:

    • 它很好,但我也需要设计
    • 您可以在字符串生成器对象中附加设计。
    • 我可以在将 asp.page 转换为 pdf 文件时使用样式(我正在使用 itextsharp.dll 进行转换)。主要问题是当我使用 'sb.Append("
      " "hello
      "); sb.Append("
      ww"; "lkl
      ");'这会将这种 div 样式写入 pdf 文件,但我需要在转换为 pdf 时应用这种样式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多