问题
I am trying to export the aspx page to pdf. I am using this code on Button2_Click, but i take a System.NullReferenceException on htmlworker.Parse(str);:
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();
回答1:
Although you can write directly to the Response.OutputStream
, doing so can mask errors sometimes. Instead I really recommend that you write to another stream such as a FileStream
or MemoryStream
. If you use the latter you can also then persist the MemoryStream
to a byte array that you can pass between functions. The code below shows this off as well as using the dispose pattern on disposable objects.
//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();
The above may still break on you depending on how you are rendering your control. You might receive a message saying something like:
Control 'xxx' of type 'yyy' must be placed inside a form tag with runat=server
You can get around this by overriding the page's VerifyRenderingInServerForm method.
public override void VerifyRenderingInServerForm(Control control) {
}
回答2:
Does your HTML contain <hr>
tag? It's not supported in HTMLworker.
回答3:
I have similar problem. I can find myself that giving HTMLTagProcessors to HTMLWorker solves this problem.
HTMLWorker htmlworker = new HTMLWorker(document, new HTMLTagProcessors(), null);
Now some HTML tags are supported by HTMLWorker.
来源:https://stackoverflow.com/questions/17167842/itextsharp-export-to-pdf-nullreferenceexception