iTextSharp未在PDF中显示HTML表格

时间:2014-04-23 10:51:45

标签: c# html asp.net itextsharp

我不明白为什么它不起作用。 这是我的代码:

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
string htmlstr = "<html><body><h1>My First Heading</h1><p>My first paragraph.</p><table border=1><tr><td>1st</td><td>2nd</td></tr><tr><td>3rd</td><td>4th</td></tr></table></body></html>";

Panel panel1 = new Panel();
panel1.Controls.Add(new LiteralControl(htmlstr));

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

我的PDF已生成,但表格未显示...

1 个答案:

答案 0 :(得分:2)

你那里有一些疯狂的代码(似乎来自here)。您已经获得了HTML字符串,但随后将其转储到ASP.Net控件中,您将进一步转储到另一个ASP.Net控件中。然后,您要求ASP.Net将控件呈现回HTML。你可以杀掉那三条或四条线。

此外,您正在写入原始HTTP响应流,然后将PDF发送到同一个流。实际上,这是你更大的问题。我强烈建议永远不要写入原始流,直到你完全处理好了。您还更改了HTTP标头,如果存在ASP.Net错误,可能会导致问题。

以下代码是对您所获得的内容的修改。我将其切换到using语句,以确保清理事情。如果您使用较旧的不受支持的iTextSharp版本,则需要将其切换回来。

string htmlstr = "<html><body><h1>My First Heading</h1><p>My first paragraph.</p><table border=1><tr><td>1st</td><td>2nd</td></tr><tr><td>3rd</td><td>4th</td></tr></table></body></html>";

//We'll store our final PDF in this
byte[] bytes;

//Read our HTML as a .Net stream
using (var sr = new StringReader(htmlstr)) {

    //Standard PDF setup using a MemoryStream, nothing special
    using (var ms = new MemoryStream()) {
        using (var pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f)) {

            //Bind a parser to our PDF document
            using (var htmlparser = new HTMLWorker(pdfDoc)) {

                //Bind the writer to our document and our final stream
                using (var w = PdfWriter.GetInstance(pdfDoc, ms)) {

                    pdfDoc.Open();

                    //Parse the HTML directly into the document
                    htmlparser.Parse(sr);

                    pdfDoc.Close();

                    //Grab the bytes from the stream before closing it
                    bytes = ms.ToArray();
                }
            }
        }
    }
}

//Assuming that the above worked we can now finally modify the HTTP response
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=BusinessUnit.pdf");
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
//Send the bytes from the PDF
Response.BinaryWrite(bytes);
Response.End();