简体   繁体   中英

how to convert html page to pdf with css using itextsharp?

This is my code :

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);

StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);

this.Page.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);** //the exception here

pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();

the error is :

Unable to cast object of type 'iTextSharp.text.html.simpleparser.CellWrapper' to type 'iTextSharp.text.Paragraph'.

What is this exception ?

I don't know if this is the answer, but I found that iTextSharp is picky about having valid html. My tests had a table that was opened twice and never closed and that took about an hour for me to notice. The exception was very similar to the one you have there.

可以使用A4大小的宽度和高度来进行html设计。

use this set od code to create pdf from html.

String htmlText = "<div>Your HTML text here</div>";

Document document = new Document();

PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\outfile.pdf", FileMode.Create));
document.Open();
iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
hw.Parse(new StringReader(htmlText));
document.Close();

Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
Response.ContentType = "application/pdf";
Response.WriteFile(Request.PhysicalApplicationPath + "\\outfile.pdf");
Response.Flush();
Response.Clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM