设置在c# web响应中创建的word文档在打印布局中打开

本文关键字:打印 文档 word 布局 创建 web 响应 设置 | 更新日期: 2023-09-27 18:07:17

我正在一个web应用程序中用html动态生成一个word文档。这工作得很好,但是我的文档在Web布局中打开。我确信我在某个地方读到一种方法,使生成的文档在打印布局中打开,但我现在找不到它。

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=ContentDocument.doc");
    StringBuilder htmlCode = new StringBuilder();
    htmlCode.Append("<html>");
    htmlCode.Append("<head><style type='"text/css'">body {font-family:arial;font-size:14.5;}</style></head>");
    htmlCode.Append("<body>");
    ... populate htmlCode ...
    htmlCode.Append("</body></html>");
    HttpContext.Current.Response.Write(htmlCode.ToString());
    HttpContext.Current.Response.End();
    HttpContext.Current.Response.Flush();

我认为这可能是在标题中添加特定内容的情况。有人知道如何让生成的文档在打印布局中打开吗?

设置在c# web响应中创建的word文档在打印布局中打开

您可以通过以下代码在打印布局中打开文档

        string strBody = string.Empty;
        strBody = @"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
        "xmlns:w='urn:schemas-microsoft-com:office:word'" +
        "xmlns='http://www.w3.org/TR/REC-html40'>";
        strBody = strBody + "<!--[if gte mso 9]>" +
        "<xml>" +
        "<w:WordDocument>" +
        "<w:View>Print</w:View>" +
        "<w:Zoom>100</w:Zoom>" +
        "</w:WordDocument>" +
        "</xml>" +
        "<![endif]-->";
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Charset = "";
    HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
    HttpContext.Current.Response.AddHeader("Content-Disposition",    "inline;filename=ContentDocument.doc");
    StringBuilder htmlCode = new StringBuilder();
    htmlCode.Append("<html>");
    htmlCode.Append("<head>"+strBody+" <style type='"text/css'">body {font-family:arial;font-size:14.5;}</style></head>");
    htmlCode.Append("<body>");
     ... populate htmlCode ...
    htmlCode.Append("</body></html>");
    HttpContext.Current.Response.Write(htmlCode.ToString());
    HttpContext.Current.Response.End();
    HttpContext.Current.Response.Flush();