iTextSharp is not showing HTML table in PDF

前端 未结 1 1468
旧时难觅i
旧时难觅i 2021-01-24 10:56

I don\'t understand why it is not working. Here is my code:

Response.ContentType = \"application/pdf\";
Response.AddHeader(\"content-disposition\", \"attachment;         


        
相关标签:
1条回答
  • 2021-01-24 11:58

    You've got some crazy code there (which appears to be from here). You've got an HTML string but then your dumping it into an ASP.Net control which you're further dumping into another ASP.Net control. Then you're asking ASP.Net to render the control back to HTML. That's three or four lines you can kill off.

    Also, you're writing to the raw HTTP response stream and then sending the PDF to the same stream. This is your bigger problem, actually. I strongly suggest never writing to the raw stream until you're absolutely done processing things. You've also changed the HTTP headers which can cause problems if there are ASP.Net errors.

    The below code is a rework of what you've got. I switched it over to using statements to ensure that things get cleaned up. If you're using an older unsupported version of iTextSharp you'll want to switch those back.

    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();
    
    0 讨论(0)
提交回复
热议问题