2013-04-04 52 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