[英]Itextsharp export to pdf NullReferenceException
我正在尝试将aspx页面导出为pdf。 我在Button2_Click上使用此代码,但我在htmlworker.Parse(str);上采用了System.NullReferenceException:
string attachment = "attachment; filename=Article.pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
dvText.RenderControl(htextw);
Document document = new Document();
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
StringReader str = new StringReader(stw.ToString());
HTMLWorker htmlworker = new HTMLWorker(document);
htmlworker.Parse(str);
document.Close();
Response.Write(document);
Response.End();
虽然您可以直接写入Response.OutputStream
,但这样做有时会掩盖错误。 相反,我真的建议您写入另一个流,如FileStream
或MemoryStream
。 如果使用后者,则还可以将MemoryStream
持久MemoryStream
可以在函数之间传递的字节数组。 下面的代码显示了这个以及在一次性物品上使用配置图案。
//We'll use this byte array as an intermediary later
Byte[] bytes;
//Basic setup for iTextSharp to write to a MemoryStream, nothing special
using (var ms = new MemoryStream()) {
using (var document = new Document()) {
using (var writer = PdfWriter.GetInstance(document, ms)) {
document.Open();
//Create our HTML worker (deprecated by the way)
HTMLWorker htmlworker = new HTMLWorker(document);
//Render our control
using (var stw = new StringWriter()) {
using (var htextw = new HtmlTextWriter(stw)) {
GridView1.RenderControl(htextw);
}
using (var str = new StringReader(stw.ToString())) {
htmlworker.Parse(str);
}
}
//Close the PDF
document.Close();
}
}
//Get the raw bytes of the PDF
bytes = ms.ToArray();
}
//At this point all PDF work is complete and we only have to deal with the raw bytes themselves
string attachment = "attachment; filename=Article.pdf";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
Response.End();
根据您渲染控件的方式,上面的内容可能仍会中断。 您可能会收到一条消息,上面写着:
Control 'xxx' of type 'yyy' must be placed inside a form tag with runat=server
你可以通过覆盖页面的VerifyRenderingInServerForm
方法来解决这个问题。
public override void VerifyRenderingInServerForm(Control control) {
}
您的HTML是否包含<hr>
标记? HTMLworker不支持它。
我有类似的问题。 我发现自己将HTMLTagProcessors提供给HTMLWorker可以解决这个问题。
HTMLWorker htmlworker = new HTMLWorker(document, new HTMLTagProcessors(), null);
现在,HTMLWorker支持一些HTML标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.