0

我正在尝试将 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();
4

3 回答 3

1

虽然您可以直接写入Response.OutputStream,但这样做有时会掩盖错误。相反,我真的建议您写入另一个流,例如 aFileStreamMemoryStream. 如果您使用后者,您还可以将其保存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) {
}
于 2013-06-18T14:39:58.740 回答
1

您的 HTML 是否包含<hr>标签?HTMLworker 不支持它。

于 2013-06-20T14:35:54.710 回答
0

我有类似的问题。我发现自己将 HTMLTagProcessors 提供给 HTMLWorker 可以解决这个问题。

HTMLWorker htmlworker = new HTMLWorker(document, new HTMLTagProcessors(), null);

现在 HTMLWorker 支持一些 HTML 标签。

于 2015-09-28T10:54:53.837 回答