[英]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.