[英]how to convert html page to pdf with css using itextsharp?
这是我的代码:
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();
错误是:
无法将类型为“ iTextSharp.text.html.simpleparser.CellWrapper”的对象转换为类型为“ iTextSharp.text.Paragraph”的对象。
这是什么例外?
我不知道这是否是答案,但是我发现iTextSharp对于具有有效的html十分挑剔。 我的测试中有一张桌子被打开过两次,并且从未关闭过,这花了一个小时让我注意到。 例外情况与您在那里的情况非常相似。
可以使用A4大小的宽度和高度来进行html设计。
使用此set od代码从html创建pdf。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.