Exemplo n.º 1
0
 public MSWord_Controller()
 {
     wordApp         = new Word.Application();
     wordApp.Visible = true;
     docs            = wordApp.Documents;
     doc             = docs.Add();
 }
Exemplo n.º 2
0
        //</Snippet6>

        static void VS2008()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            object useDefaultVal = Type.Missing;

            Word.Document doc = docs.Add(ref useDefaultVal, ref useDefaultVal,
                                         ref useDefaultVal, ref useDefaultVal);

            object n = 0;

            Word.Range range = doc.Range(ref n, ref n);

            range.InsertAfter("Testing, testing, testing. . .");

            //<Snippet14>
            // Call to ConvertToTable in Visual C# 2008 or earlier. This code
            // is not part of the solution.
            var    missing   = Type.Missing;
            object separator = ",";

            range.ConvertToTable(ref separator, ref missing, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing);
            //</Snippet14>
        }
Exemplo n.º 3
0
        //<Snippet6>
        static void DisplayInWord()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            Word.Document doc = docs.Add();
        }
Exemplo n.º 4
0
        public Word.Document CreateWordDoc()
        {
            try
            {
                //新建一个文档
                m_WordDocs = m_WordApp.Documents;
                m_WordDoc  = m_WordDocs.Add(ref missing, ref missing, ref missing, ref missing);
            }
            catch (System.Exception)
            {
                m_WordDoc = null;
            }

            return(m_WordDoc);
        }
Exemplo n.º 5
0
        static void DisplayInWord()
        {
            var wordApp = new Word.Application();

            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc.
            Word.Document doc = docs.Add();

            //<Snippet7>
            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");
            //</Snippet7>

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table.
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            //<Snippet9>
            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");
            //</Snippet9>

            // Change to a single column with three rows..
            //<Snippet10>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);
            //</Snippet10>

            // Format the table.
            //<Snippet11>
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                                 Format: Word.WdTableFormat.wdTableFormatElegant);
            //</Snippet11>
        }
Exemplo n.º 6
0
		/// <summary>
		/// Word operation
		/// </summary>
		/// <param name="command"></param>
		/// <param name="sArg"></param>
		/// <param name="nArg1"></param>
		/// <param name="nArg2"></param>
		/// <param name="nArg3"></param>
		/// <param name="nArg4"></param>
		/// <returns></returns>
		public static string Call(
			string command,
			string sArg,
			int nArg1,
			int nArg2,
			int nArg3,
			int nArg4,
			bool bArg)
		{

			object missingObj = System.Reflection.Missing.Value; // missing object parameter 

			if (SS.I.DebugFlags[5] != null) // dump out command for debug
			{
				ClientLog.Message("Call " + command + " " + sArg);
			}

			try // catch any Word exception
			{

				//******************************************************************************  
				if (Lex.Eq(command, "CreateObject"))  // create the word object
				//******************************************************************************  
				{
					try
					{
						WdApp = new Microsoft.Office.Interop.Word.Application();
					}
					catch (Exception ex)
					{
						return "Word failed to start";
					}

				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Quit"))
				{ // quit application
					//******************************************************************************  

					//Microsoft.Office.Interop.Word.Application.
					WdApp.Quit(ref missingObj, ref missingObj, ref missingObj);

					//	AutoWrap(DISPATCH_METHOD, NULL, WdApp, L"Quit", 0);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.SetWidth"))
				{
					//******************************************************************************  
					WdSel.Cells.SetWidth(nArg1, WdRulerStyle.wdAdjustNone);
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg1,nArg1);  // width in points
	SETLONG(Arg2,wdAdjustNone); // ruler style, required sArg
	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Setwidth", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "DeleteObject"))
				{
					//******************************************************************************  
					WdSel = null;
					WdTable = null;
					WdTables = null;
					WdDoc = null;
					WdDocs = null;
					WdApp = null;
#if false
	// Release references, must do lower to higher level...
	release_obj(WdTemp);
	release_obj(WdSel);
	release_obj(WdTable);
	release_obj(WdTables);
	release_obj(WdDoc);
	release_obj(WdDocs);
	release_obj(WdApp);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Close"))
				{
					//******************************************************************************  
					//      excelobj.ActiveWorkbook.Close False ' no prompt for save
					((_Document)WdDoc).Close(ref missingObj, ref missingObj, ref missingObj);

					//	SETLONG(SaveChanges,wdSaveChanges); // don't prompt
					//	AutoWrap(DISPATCH_METHOD, NULL, WdDoc, L"Close", 1, SaveChanges);
					//	VariantClear(&SaveChanges);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Documents.Add"))
				{ // Add a new document
					//******************************************************************************  

					WdDocs = WdApp.Documents;
					WdDoc = WdDocs.Add(ref missingObj, ref missingObj, ref missingObj, ref missingObj);

#if false
	release_obj(WdDocs); // Get active documents
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdApp, L"Documents", 0);   // Get Documents collection
	WdDocs = result.pdispVal;

	release_obj(WdDoc); // Add new document
	AutoWrap(DISPATCH_METHOD, &result, WdDocs, L"Add", 0);
	WdDoc = result.pdispVal;
#endif

					if (WdDoc == null) return ("Error adding document");
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "EndKey"))
				{
					//******************************************************************************  
					Object unit = nArg1;
					WdSel.HomeKey(ref unit, ref missingObj);

					//	SETLONG(Arg,nArg1); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Name"))
				{
					//******************************************************************************  
					//      WordObj.Selection.Font.Name = sArg
					WdSel.Font.Name = sArg;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETSTR(Arg,sArg);  // set font name
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Name", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Size"))
				{
					//******************************************************************************  
					//      WordObj.Selection.Font.Size = sArg

					WdSel.Font.Size = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Size", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Bold"))
				//******************************************************************************  
				{
					if (bArg) WdSel.Font.Bold = -1;
					else WdSel.Font.Bold = 0;
				}

	//******************************************************************************  
				else if (Lex.Eq(command, "Font.Italic"))
				//******************************************************************************  
				{
					if (bArg) WdSel.Font.Italic = -1;
					else WdSel.Font.Italic = 0;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Font.Subscript"))
				//******************************************************************************  
				{
					WdSel.Font.Subscript = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Subscript", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Superscript"))
				{
					//******************************************************************************  
					WdSel.Font.Superscript = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Superscript", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "SetDefaultCellStyle"))
				//******************************************************************************  
				{ // Cell style (e.g. backcolor) automatically carries down do successive
					// rows and must be explicitly reset

					//			int rgbBlack = 0;
					//			if (WdSel.Font.Color != (Microsoft.Office.Interop.Word.WdColor)rgbBlack)
					//				WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgbBlack;

					//			int rgbWhite = 255 + 255 * 256 + 255 * 65536;
					//			if (WdSel.Cells.Shading.BackgroundPatternColor != (Microsoft.Office.Interop.Word.WdColor)rgbWhite)
					//				WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgbWhite;

					if (WdSel.Font.Color != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic)
						WdSel.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;

					if (WdSel.Cells.Shading.BackgroundPatternColor != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic)
						WdSel.Cells.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Color"))
				//******************************************************************************  
				{
					Color c = Color.FromArgb(nArg1);
					int rgb = c.R + c.G * 256 + c.B * 65536;
					WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgb;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "BackColor"))
				//******************************************************************************  
				{
					Color c = Color.FromArgb(nArg1);
					int rgb = c.R + c.G * 256 + c.B * 65536;
					WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgb;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "HomeKey"))
				{
					//******************************************************************************  
					Object unit = nArg1;
					WdSel.HomeKey(ref unit, ref missingObj);
#if false
	SETLONG(Arg,nArg1); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg);
	VariantClear(&Arg);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InlineShapes.AddPicture"))
				{ // insert image from file
					//******************************************************************************  
					InlineShape ils = WdSel.InlineShapes.AddPicture(sArg, ref missingObj, ref missingObj, ref missingObj);
					ils.Width = nArg1;
					ils.Height = nArg2;
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"InlineShapes", 0);
	WdTemp = result.pdispVal;

	SETSTR(Filename,sArg);  // filename
	SETLONG(Width,nArg1); // in points
	SETLONG(Height,nArg2);

	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"AddPicture", 1, Filename);
	release_obj(WdTemp);
	WdTemp = result.pdispVal; // new shape object

	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Width", 1, Width);

	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Height", 1, Height);

	VariantClear(&Filename);
	VariantClear(&Width);
	VariantClear(&Height);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertBreak"))
				{
					//******************************************************************************  
					object type = nArg1;
					WdSel.InsertBreak(ref type);

					//	SETLONG(Arg,nArg1); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertBreak", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertSymbol"))
				{
					//******************************************************************************  
					// InsertSymbol(CharacterNumber as Long, Font as String)
					int characterNumber = nArg1;
					object font = sArg;
					WdSel.InsertSymbol(characterNumber, ref font, ref missingObj, ref missingObj);
#if false
	SETLONG(Arg,nArg1); // get char number
	SETSTR(Arg2,sArg); // get font
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertSymbol", 2, Arg2, Arg);
	VariantClear(&Arg);
	VariantClear(&Arg2);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.Merge"))
				{ // merge cells together
					//******************************************************************************  
					WdSel.Cells.Merge();
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0);
	WdTemp = result.pdispVal;

	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Merge", 0);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveLeft"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;

					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveLeft(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveLeft", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveRight"))
				{ // units, count, extend
					//******************************************************************************  
					object extend;
					if (nArg2 <= 0) nArg2 = 1;

					object unit = nArg1;
					object count = nArg2;
					if (nArg3 <= 0) extend = missingObj;
					else extend = nArg3;

					WdSel.MoveRight(ref unit, ref count, ref extend);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	SETLONG(Arg3,nArg3); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveRight", 3, Arg3, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
	VariantClear(&Arg3);
#endif

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveDown"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;
					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveDown(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveDown", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveUp"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;
					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveUp(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveUp", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.Orientation"))
				{
					//******************************************************************************  

					if (nArg1 == 0)
						WdSel.PageSetup.Orientation = WdOrientation.wdOrientPortrait;
					WdSel.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
#if false
	release_obj(WdTemp);
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"PageSetup", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1); 
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Orientation", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.Margins"))
				{
					//******************************************************************************  
					WdSel.PageSetup.TopMargin = nArg1;
					WdSel.PageSetup.BottomMargin = nArg2;
					WdSel.PageSetup.LeftMargin = nArg3;
					WdSel.PageSetup.RightMargin = nArg4;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.PageSize"))
				{
					//******************************************************************************  
					WdSel.PageSetup.PageWidth = nArg1;
					WdSel.PageSetup.PageHeight = nArg2;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "ParagraphFormat.Alignment"))
				{
					//******************************************************************************  
					WdSel.ParagraphFormat.Alignment = (WdParagraphAlignment)nArg1;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.VerticalAlignment"))
				//******************************************************************************  
				{
					WdSel.Cells.VerticalAlignment = (WdCellVerticalAlignment)nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Paste"))
				//******************************************************************************  
				{
					WdSel.Paste();
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PasteSpecial"))
				{
					//******************************************************************************  
					//	PasteSpecial(IconIndex, Link, Placement, DisplayAsIcon, DataType)

					object iconIndex = 0;
					object link = false;
					object placement = InLine;
					object displayAsIcon = false;
					object dataType = nArg1; // set type of data to paste

					//	ClientLog.Message("Before PasteSpecial"); // TST & PRD 
					WdSel.PasteSpecial(ref iconIndex, ref link, ref placement, ref displayAsIcon,
						ref dataType, ref missingObj, ref missingObj);
					//	ClientLog.Message("After PasteSpecial");
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertStructure"))
				//******************************************************************************  
				// Selection.InlineShapes.AddOLEObject ClassType:="ISISServer", FileName:= _
				//  "C:\Isis\sketch1-small.skc", LinkToFile:=False, DisplayAsIcon:=False
				// This is significantly slower than a paste
				{
					object classType = "ISISServer";
					object fileName = sArg;

					WdSel.InlineShapes.AddOLEObject(
						ref classType,
						ref fileName,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Rows.AllowBreakAcrossPages"))
				{ // keep all contents of row on same page
					//******************************************************************************  

					WdSel.Rows.AllowBreakAcrossPages = nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Rows.HeadingFormat"))
				{ // mark rows as headings
					//******************************************************************************  

					WdSel.Rows.HeadingFormat = nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "SaveAs"))
				{ // save file in .doc format
					//******************************************************************************  
					try { File.Delete(sArg); } // delete any existing file
					catch (Exception ex) { };
					object fileName = sArg;
					object fileFormat = WdSaveFormat.wdFormatDocument;

					WdDoc.SaveAs(
						ref fileName, // FileName 
						ref fileFormat, // FileFormat 
						ref missingObj, // LockComments 
						ref missingObj, // Password 
						ref missingObj, // AddToRecentFiles 
						ref missingObj, // WritePassword 
						ref missingObj, // ReadOnlyRecommended 
						ref missingObj, // EmbedTrueTypeFonts 
						ref missingObj, // SaveNativePictureFormat
						ref missingObj,	// SaveFormsData 
						ref missingObj,	// SaveAsAOCELetter
						ref missingObj,	// Encoding
						ref missingObj,	// InsertLineBreaks 
						ref missingObj, // AllowSubstitutions 
						ref missingObj, // LineEnding 
						ref missingObj); // AddBiDiMarks
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "ScreenUpdating"))
				{
					//******************************************************************************  
					WdApp.ScreenUpdating = bArg;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "SelectColumn"))
				{ // select current column of table
					//******************************************************************************  
					WdSel.SelectColumn();
					//	AutoWrap(DISPATCH_METHOD, NULL, WdSel, L"SelectColumn", 0); 
					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "SelectRow"))
				{ // select current row of table
					//******************************************************************************  
					WdSel.SelectRow();

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "Tables.Add"))
				{ // number of rows & cols supplied
					//******************************************************************************  

					WdTables = WdDoc.Tables;
					Microsoft.Office.Interop.Word.Range range = WdSel.Range;
					int numRows = nArg1;
					int numCols = nArg2;
					WdTable = WdTables.Add(range, numRows, numCols, ref missingObj, ref missingObj);
					WdTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
					WdTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TableSelect"))
				{
					//******************************************************************************  

					WdTable.Select();

					UpdateSelection(); // update selection
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TypeParagraph"))
				{
					//******************************************************************************  
					WdSel.TypeParagraph();

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TypeText"))
				{
					//******************************************************************************  
					WdSel.TypeText(sArg);
					//	SETSTR(Arg,sArg); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"TypeText", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "Visible"))
				{
					//******************************************************************************  
					WdApp.Visible = bArg;
#if false
	SETBOOL(True,1);
	SETBOOL(False,0);
	if (strcmpi((CCP)sArg,"true)) 
	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, True);

	else 	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, False);
#endif
				}

		//******************************************************************************  
				else throw new Exception("WordOp - Invalid operation " + command);
				//******************************************************************************  

				return ""; // everything must be ok

			} // end of try
Exemplo n.º 7
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.hasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Microsoft.Office.Interop.Word.Options   wdOptions      = null;
                Microsoft.Office.Interop.Word.Documents documents      = null;
                Microsoft.Office.Interop.Word.Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        Converter.releaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Microsoft.Office.Interop.Word.Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.releaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Microsoft.Office.Interop.Word.Window docWin     = null;
                    Microsoft.Office.Interop.Word.View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        docWinView.RevisionsView            = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments = false;
                    }
                    catch (SystemException) { }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        Converter.releaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        updateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    Converter.releaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    Converter.releaseCOMObject(docWinView);
                    Converter.releaseCOMObject(docWin);
                }

                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.resetValue(ref wdOptions);
                }

                Converter.releaseCOMObject(wdOptions);
                Converter.releaseCOMObject(documents);
                Converter.releaseCOMObject(doc);
                Converter.releaseCOMObject(tmpl);
                Converter.releaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    closeWordApplication(word);
                }
                Converter.releaseCOMObject(word);
            }
        }
Exemplo n.º 8
0
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // 创建一个Microsoft Word实例并令其不可见

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // 创建一个新的文档

                oDocs = oWord.Documents;
                oDoc  = oDocs.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // 插入段落

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // 将文档保存为.docx文件并关闭

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
                oDoc.SaveAs(ref fileName, ref fileFormat, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // 退出Word应用程序

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // 通过在所有访问对象上显示调用Marshal.FinalReleaseComObject方法
                // 释放非托管Word COM资源
                // 见 http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
Exemplo n.º 9
0
        private bool CreateAndShowMyWordDocument()
        {
            try
            {
                // Declaration of the necessary Word Interop variables
                Word.Application objWord = null;
                GetWordInstance(ref objWord);
                Word.Documents objDocs = objWord.Documents;
                Word.Document  objDoc;

                // Declaration and initialization of other necessary variables
                object objFile    = AppDomain.CurrentDomain.BaseDirectory + "MyWordTemplates.dotm";
                object objVisible = true;
                object objMissing = System.Reflection.Missing.Value;

                // Creation of the Word document
                objDoc = objDocs.Add(ref objFile, ref objMissing, ref objMissing, ref objVisible);
                object fname = String.Format("{0}{1}.docx", AppDomain.CurrentDomain.BaseDirectory + "MyWordDoc", Properties.Settings.Default.DocNum++);
                objDoc.SaveAs(ref fname, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);

                // Show the Word document
                objWord.Visible = true;
                objWord.ActiveWindow.Activate();

                // Fill the Word text placeholder with our bounded variables
                if (!SetWordBookmarks(objWord, objDoc.Bookmarks, "FullAddressSender", FullAddressSender))
                {
                    return(false);
                }
                if (!SetWordBookmarks(objWord, objDoc.Bookmarks, "FirstName", FirstName))
                {
                    return(false);
                }
                if (!SetWordBookmarks(objWord, objDoc.Bookmarks, "Surname", Surname))
                {
                    return(false);
                }
                if (!SetWordBookmarks(objWord, objDoc.Bookmarks, "StreetHouseNumber", StreetHouseNumber))
                {
                    return(false);
                }
                if (!SetWordBookmarks(objWord, objDoc.Bookmarks, "PostcodeCity", PostcodeCity))
                {
                    return(false);
                }

                // Activate and save the document
                objDoc.Activate();
                objDoc.Save();

                // Release of the Interop resources
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objWord);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(objDocs);

                return(true);
            }
            catch (Exception ex)
            {
                Console.Beep();
                Console.Beep();
                Message = String.Format("EXCEPTION: {0}", ex.ToString());
                return(false);
            }
        }
Exemplo n.º 10
0
 public void New()
 {
     doc = docs.Add();
 }
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // Create an instance of Microsoft Word and make it invisible.

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // Create a new Document.

                oDocs = oWord.Documents;
                oDoc  = oDocs.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // Insert a paragraph.

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // Save the document as a docx file and close it.

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
                oDoc.SaveAs(ref fileName, ref fileFormat, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // Quit the Word application.

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }