網(wǎng)上的代碼很多,但拿過來肯定不能直接運行。因為需要配置一下。
1工程添加引用COM:Microsoft Word 14.0 Object Library
2修改WEB.CONFIG,在<system.web>加入:<identity impersonate="true"/>
3開始-》運行:dcomcnfg,會顯示出“組件服務”管理器。打開“組件服務-》計算機-》我的電腦-》DCOM 配置”,找到“Microsoft Word 97 - 2003 文檔”,單擊右鍵,選擇“屬性”。在“屬性”對話框中單擊“安全”選項卡,在“啟動和激活權限”處選擇“自定義”,再單擊右邊的“編輯”,在彈出的對話框中添加“ASPNET”(在IIS6中是NETWORD SERVICE)用戶,給予“本地啟動”和“本地激活”的權限,單擊“確定”,關閉“組件服務”管理器。
4 using Microsoft.Office.Interop.Word;
5編碼:
protected void Page_Load(object sender, EventArgs e)
{
WaterMarkToWord("d:\\a.jpg", "d:\\d.docx", "d:\\c.docx");// d:\\d.docx可以換成"d:\\b.doc",
}
public void WaterMarkToWord(string imgName, object srcFileName, object dstFileName)
{
object Nothing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application wordAppObj = null;
Microsoft.Office.Interop.Word.Document wordDoc = null;
try
{
object obj = true;
wordAppObj = new Microsoft.Office.Interop.Word.Application();
wordDoc = wordAppObj.Documents.Open(ref srcFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
Shape oShape;
wordDoc.ActiveWindow.View.Type = WdViewType.wdOutlineView;
wordDoc.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
//WordDoc.ActiveWindow.ActivePane.Selection.InsertAfter(DateTime.Now.ToString("yyyyMMddhhssmm"));
object left = wordDoc.ActiveWindow.Width / 4;
object top = wordDoc.ActiveWindow.Height / 2;
oShape = wordDoc.ActiveWindow.ActivePane.Selection.HeaderFooter.Shapes.AddPicture(imgName, ref Nothing,
ref Nothing, ref left, ref top, ref Nothing, ref Nothing, ref Nothing);
oShape.WrapFormat.Type = WdWrapType.wdWrapInline;
oShape.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendBehindText);
wordDoc.SaveAs(ref dstFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
catch (Exception ex)
{
}
finally
{
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordAppObj.Quit(ref Nothing, ref Nothing, ref Nothing);
}
}
注意藍色的地方。
好了,可以用了,弄個a.jpg圖片,弄個b.doc或b.docx都可以的,效果就出來了,不過具體的圖片的位置需要調。