虽然您可以直接写入Response.OutputStream
,但这样做有时会掩盖错误。相反,我真的建议您写入另一个流,例如 aFileStream
或MemoryStream
. 如果您使用后者,您还可以将其保存MemoryStream
到可以在函数之间传递的字节数组中。下面的代码显示了这一点以及在一次性对象上使用 dispose 模式。
//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) {
}