Itextsharp 我想把html页面转换成pdf文件

Itextsharp 我想把html页面转换成pdf文件,itextsharp,Itextsharp,我想将HTML页面转换为PDF文档,但我的程序显示错误pdfptable构造函数中的列数必须大于零 这是我的代码: Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=ulcact.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw

我想将HTML页面转换为PDF文档,但我的程序显示错误
pdfptable构造函数中的列数必须大于零

这是我的代码:

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ulcact.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
tb1.RenderControl(hw);
Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
StringReader sr = new StringReader(sw.ToString());
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
htmlparser.Parse(sr);//error should be gone
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End(); 

什么会导致此错误以及如何修复此错误?

导致此错误的原因可能有很多,但当我遇到此问题时,它是由于不正确或脏的HTML造成的

首先,请检查您的StringWriter是否为空。然后调试代码,在htmlparser.Parse(sr)之前查看代码中的内容;线路


第二,如果在调试时看到HTML是脏的,那么必须清理HTML。有一个库可以实现这一点,它的名字叫做HTMLTidy。在stackoverflow上搜索它,你会发现许多关于如何使用它的帖子。使用HTMLTidy清理HTML,然后给htmlparser.Parse方法清理HTML,它应该可以工作。

您的stringwriter为空。尝试向其中添加一些html内容。