我正在尝试将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();
答案 0 :(得分:1)
虽然可以直接写入Response.OutputStream
,但这样做有时会掩盖错误。相反,我真的建议您写入另一个流,例如FileStream
或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) {
}
答案 1 :(得分:1)
您的HTML是否包含<hr>
标记?它在HTMLworker中不受支持。
答案 2 :(得分:0)
我有类似的问题。我发现自己将HTMLTagProcessors提供给HTMLWorker可以解决这个问题。
HTMLWorker htmlworker = new HTMLWorker(document, new HTMLTagProcessors(), null);
现在,HTMLWorker支持一些HTML标记。