2013-04-04 54 views
0

我在Web应用程序中动态生成带有html的Word文档。这工作正常但我的文档在Web布局中打开。我确定我在某处阅读了某种方式来使生成的文档在“打印版式”中打开,但我现在无法在任何地方找到它。设置在C#web中创建的Word文档在打印布局中打开的响应

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(); 

我认为这可能是一个特定的标题添加的东西的情况。有谁知道如何让生成的文档在打印布局中打开?

回答

2

您可以通过下面的代码

 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(); 
+0

非常感谢您打开打印布局文档。 – stevepkr84 2013-04-04 09:49:07

+0

你至少应该有7个upvotes – Daria 2015-04-24 18:33:52

+0

我把这个直接放到html中,它不工作:( – Murphybro2 2017-08-24 10:58:48