/// <summary> /// Объединение нескольких документов word в один /// </summary> /// <param name="filePathOutput">Имя выходного файла</param> /// <param name="mergeDocs">Массив имен файлов, из которых будет скопировано содержимое в выходной файл</param> public static void MergerDocs(string filePathOutput, string[] mergeDocs) { object sectionBreak = Word.WdBreakType.wdSectionBreakNextPage; Word.Application app = null; try { app = new Word.Application(); Word.Document doc = app.Documents.Add(); Word.Selection selection = app.Selection; for (int i = 0; i < mergeDocs.Length; i++) { selection.InsertFile(mergeDocs[i]); if (i != mergeDocs.Length - 1) { selection.InsertBreak(sectionBreak); } } doc.SaveAs2(filePathOutput); doc.Close(); } finally { try { app.Quit(); } catch (Exception) { } } }
public void SetPageBreak() { if (m_pSelection != null) { m_pSelection.InsertBreak(7); } }
/// <summary> /// A function that merges Microsoft Word Documents that uses a template specified by the user /// </summary> /// <param name="filesToMerge">An array of files that we want to merge</param> /// <param name="outputFilename">The filename of the merged document</param> /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param> /// <param name="documentTemplate">The word document you want to use to serve as the template</param> private void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate) { object defaultTemplate = documentTemplate; object missing = System.Type.Missing; object pageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; object outputFile = outputFilename; // Create a new Word application Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application(); if (filesToMerge.Count() == 1) { pageBreak = false; } try { // Create a new file based on our template Microsoft.Office.Interop.Word._Document wordDocument = wordApplication.Documents.Add(ref defaultTemplate, ref missing, ref missing, ref missing); // Make a Word selection object. Microsoft.Office.Interop.Word.Selection selection = wordApplication.Selection; int index = 0; // Loop thru each of the Word documents foreach (string file in filesToMerge) { // Insert the files to our template selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing); //Do we want page breaks added after each documents? if (insertPageBreaks && index != filesToMerge.Count() - 1) { selection.InsertBreak(ref pageBreak); } index++; } // Save the document to it's output file. wordDocument.SaveAs(ref outputFile, 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); // Clean up! wordDocument.Close(ref missing, ref missing, ref missing); wordDocument = null; } catch (Exception ex) { //I didn't include a default error handler so i'm just throwing the error throw ex; } finally { // Finally, Close our Word application wordApplication.Quit(ref missing, ref missing, ref missing); } }
public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate) { object defaultTemplate = documentTemplate; object missing = System.Type.Missing; object pageBreak = Word.WdBreakType.wdPageBreak; object outputFile = outputFilename; Word._Application wordApplication = new Word.Application(); try { Word._Document wordDocument = wordApplication.Documents.Add(ref defaultTemplate, ref missing, ref missing, ref missing); Word.Selection selection = wordApplication.Selection; foreach (string file in filesToMerge) { //selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing); selection.InsertFile(file); if (insertPageBreaks) { selection.InsertBreak(ref pageBreak); } } wordDocument.SaveAs(ref outputFile, 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); wordDocument = null; } catch (Exception ex) { //TODO throw ex; } finally { wordApplication.Quit(ref missing, ref missing, ref missing); } }
public static bool Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate, out string errorString) { errorString = string.Empty; object defaultTemplate = documentTemplate; object missing = System.Type.Missing; object oTrue = true; object oFalse = false; //object pageBreak = Word.WdBreakType.wdPageBreak; object pageBreak = Word.WdBreakType.wdSectionBreakNextPage; object outputFile = outputFilename; if (filesToMerge.Length == 0) { return(true); } for (int i = 0; i < filesToMerge.Length - 1; i++) { if (Path.GetExtension(filesToMerge[i]).ToUpper() == ".PDF") { errorString = "MultiDocumentMerger.Merge() should be given word docs to merge, but pdf file sent in."; return(false); } } if (filesToMerge.Length == 1) { if (Path.GetExtension(outputFilename).ToUpper() == ".PDF") { string _errorString = null; FormatConverter.WordToPDF(filesToMerge[0], outputFilename, out _errorString); if (_errorString != string.Empty) { errorString = _errorString; return(false); } } else { System.IO.File.Copy(filesToMerge[0], outputFilename); } return(true); } // Create a new Word application Word._Application wordApplication = new Word.Application(); try { // Create a new file based on our template object template = (documentTemplate == null) ? missing : defaultTemplate; // this doesnt keep the header info and the formatting (and background images) are all screwed up //Word._Document wordDocument = wordApplication.Documents.Add(ref template, ref missing, ref missing, ref missing); // for some reason this is placed at the end of the documents, so put the last doc in, then below add first up to 2nd last doc object lastFile = filesToMerge[filesToMerge.Length - 1]; Word._Document wordDocument = wordApplication.Documents.Add(ref lastFile, ref missing, ref missing, ref missing); // Make a Word selection object. Word.Selection selection = wordApplication.Selection; // Loop thru each of the Word documents for (int i = 0; i < filesToMerge.Length - 1; i++) { // Insert the files to our template selection.InsertFile( filesToMerge[i] , ref missing , ref missing , ref missing , ref missing); //Do we want page breaks added after each documents? if (i < (filesToMerge.Length - 1) && insertPageBreaks) { selection.InsertBreak(ref pageBreak); } } // Save the document to it's output file. object fileFormat = System.IO.Path.GetExtension(outputFile.ToString()).ToUpper() == ".PDF" ? Word.WdSaveFormat.wdFormatPDF : missing; wordDocument.SaveAs( ref outputFile , 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); // Clean up! wordDocument.Close(ref oFalse, ref missing, ref missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument); wordDocument = null; return(true); } catch (System.Exception ex) { errorString = ex.Message; } finally { //RELEASE WORD ITSELF wordApplication.Quit(ref missing, ref missing, ref missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplication); wordApplication = null; GC.Collect(); } return(false); }
/// <summary> /// A function that merges Microsoft Word Documents that uses a template specified by the user /// </summary> /// <param name="filesToMerge">An array of files that we want to merge</param> /// <param name="outputFilename">The filename of the merged document</param> /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param> /// <param name="documentTemplate">The word document you want to use to serve as the template</param> public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate) { object defaultTemplate = documentTemplate; object missing = System.Type.Missing; object pageBreak = Word.WdBreakType.wdSectionBreakNextPage; object outputFile = outputFilename; // Create a new Word application Word._Application wordApplication = new Word.Application( ); try { // Create a new file based on our template Word.Document wordDocument = wordApplication.Documents.Add( ref missing , ref missing , ref missing , ref missing); // Make a Word selection object. Word.Selection selection = wordApplication.Selection; //Count the number of documents to insert; int documentCount = filesToMerge.Length; //A counter that signals that we shoudn't insert a page break at the end of document. int breakStop = 0; // Loop thru each of the Word documents foreach (string file in filesToMerge) { breakStop++; // Insert the files to our template selection.InsertFile( file , ref missing , ref missing , ref missing , ref missing); //Do we want page breaks added after each documents? if (insertPageBreaks && breakStop != documentCount) { selection.InsertBreak(ref pageBreak); } } // Save the document to it's output file. wordDocument.SaveAs( ref outputFile , 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); // Clean up! wordDocument = null; } catch (Exception ex) { //I didn't include a default error handler so i'm just throwing the error throw ex; } finally { // Finally, Close our Word application wordApplication.Quit(ref missing, ref missing, ref missing); } }
public static void AddMerge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate) { object defaultTemplate = documentTemplate; object missing = System.Type.Missing; object pageBreak = Word.WdBreakType.wdPageBreak; object outputFile = outputFilename; // Create a new Word application Word._Application wordApplication = new Word.Application(); try { // Create a new file based on our template Word._Document wordDocument = wordApplication.Documents.Add( ref defaultTemplate , ref missing , ref missing , ref missing); // Make a Word selection object. Word.Selection selection = wordApplication.Selection; // Loop thru each of the Word documents foreach (string file in filesToMerge) { // Insert the files to our template selection.InsertFile( file , ref missing , ref missing , ref missing , ref missing); //Do we want page breaks added after each documents? if (insertPageBreaks) { selection.InsertBreak(ref pageBreak); } } // Save the document to it's output file. wordDocument.SaveAs( ref outputFile , 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); // Clean up! wordDocument = null; } catch (Exception ex) { throw ex; } finally { wordApplication.Quit(ref missing, ref missing, ref missing); } }
/// <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
private void btnCreateDoc_Click(object sender, RoutedEventArgs e) { if (CheckForm() == false) { return; } bool failed = false; btnCreateDoc.IsEnabled = false; btnCreateDoc.Content = "Working"; //Everything has to be an object(COM) to pass to word. object strFileName = txtPath.Text + "\\" + txtAssignment.Text + " - " + txtStudent.Text + ".doc"; try { File.Copy(txtPath.Text + "\\GradingTemplate.doc", (string)strFileName, true); } catch { failed = true; MessageBox.Show("Error can't access " + strFileName); } if (failed == false) { word.Application wordApp = new word.Application(); wordApp.Visible = WatchWordWork; wordApp.WindowState = word.WdWindowState.wdWindowStateNormal; object missing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = true; word.Document doc = wordApp.Documents.Open(ref strFileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); // Activate the document so it shows up in front doc.Activate(); //I don't know how to search header of word doc. Works in old word files, not docx //SearchReplace("#1", strCourseName, wordApp); //SearchReplace("#2", cmbProfessor.Text, wordApp); SearchReplace("#3", txtStudent.Text, wordApp); SearchReplace("#4", txtAssignment.Text, wordApp); //This magic lets me use the checkbox name as the ms word field name //You can just add a checkbox to the form and a spot on the template //and it will automatically detect it with no code changes. foreach (var control in this.GetChildren()) { if (control is CheckBox) { CheckBox chkBox = control as CheckBox; if (chkBox.IsChecked == true && chkBox != chkAppend) { string newText = chkBox.Content.ToString(); //late checkbox is special if (chkBox == chkLate) { newText += " " + howLate.ToString() + " days"; } SearchReplace(magicspace + chkBox.Content.ToString(), magicx + newText, wordApp); } } } //this is a terrible way to do this... //but I'm short on time, I have Physics to do. SearchReplace("#5", txtMemoryLeak.Text, wordApp); SearchReplace("#6", txtIncorrectStatement.Text, wordApp); SearchReplace("#7", txtRedundantCode.Text, wordApp); SearchReplace("#8", txtBasemember.Text, wordApp); SearchReplace("#9", txtDestructor.Text, wordApp); SearchReplace("#10", txtOperatorEq.Text, wordApp); SearchReplace("#11", txtCopyConstructor.Text, wordApp); SearchReplace("#12", txtConstructor.Text, wordApp); SearchReplace("#13", txtNotSeperatehcpp.Text, wordApp); //commenting section SearchAndType("#14", txtMissingFunctionality.Text.ToString(), wordApp); SearchAndType("#15", txtRuntimeCrash.Text.ToString(), wordApp); SearchAndType("#16", txtLogicError.Text.ToString(), wordApp); SearchAndType("#17", txtComment.Text.ToString(), wordApp); //insert the comments at the end. //wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing); //wordApp.Selection.TypeText("\r\n\r\nComments: " + txtComment.Text); doc.Save(); //Merge to one doc if (chkAppend.IsChecked == true) { doc.Close(); object masterFile = txtPath.Text + "\\" + strCourseName + " - " + txtAssignment.Text + ".doc"; if (!File.Exists((string)masterFile)) { File.Copy((string)strFileName, (string)masterFile); } else { word.Document d = wordApp.Documents.Open(ref masterFile, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); word.Selection selection = wordApp.Selection; //should put this in function. //Go to end of page. Object toWhat = word.WdGoToItem.wdGoToLine; Object toWhich = word.WdGoToDirection.wdGoToLast; wordApp.Selection.GoTo(toWhat, toWhich, ref missing, ref missing); wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing); object pageBreak = word.WdBreakType.wdPageBreak; selection.InsertBreak(ref pageBreak); selection.InsertFile((string)strFileName); d.Save(); d.Close(); //delete old student templated file. File.Delete((string)strFileName); } } if (!WatchWordWork) { wordApp.Quit(); } } Clear(); btnCreateDoc.Content = "Create Doc"; btnCreateDoc.IsEnabled = true; }
public static string MergeFiles(string[] filesToMerge, bool insertPageBreaks, string resultName) { object missing = System.Type.Missing; object pageBreak = Word.WdBreakType.wdPageBreak; object outputFile = null; if (resultName == null) { outputFile = Path.GetTempFileName(); } else { outputFile = Path.Combine(Path.GetTempPath(), resultName); File.Move(Path.GetTempFileName(), outputFile.ToString()); } Word._Application wordApplication = null; Word._Document wordDocument = null; try { wordApplication = new Word.Application(); wordDocument = wordApplication.Documents.Add(ref outputFile, ref missing, ref missing, ref missing); Word.Selection selection = wordApplication.Selection; foreach (string file in filesToMerge) { selection.InsertFile(file, ref missing, ref missing, ref missing, ref missing); if (insertPageBreaks) { selection.InsertBreak(ref pageBreak); } } wordDocument.PageSetup.TopMargin = 20; wordDocument.PageSetup.BottomMargin = 20; wordDocument.PageSetup.LeftMargin = 50; //wordDocument.Paragraphs.CharacterUnitFirstLineIndent = 1.5F; wordDocument.SaveAs(ref outputFile); Console.WriteLine("Generated file after merge=" + outputFile); return(outputFile.ToString()); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); if (outputFile != null) { File.Delete(outputFile.ToString()); } } finally { if (wordDocument != null) { wordDocument.Close(); wordDocument = null; } if (wordApplication != null) { wordApplication.Quit(); wordApplication = null; } foreach (string path in filesToMerge) { if (File.Exists(path)) { File.Delete(path); } } } return(null); }
private void btnSave_Click(object sender, EventArgs e) { bool failed = false; btnSave.Enabled = false; btnSave.Text = "Working"; //Everything has to be an object(COM) to pass to word. object strFileName = txtPath.Text + "\\" + cmboHomework.Text + " - " + cmboStudentName.Text + ".doc"; try { File.Copy(txtPath.Text + "\\GradingTemplate.doc", (string)strFileName, true); } catch { failed = true; MessageBox.Show("Error can't access " + strFileName); } if (failed == false) { word.Application wordApp = new word.Application(); wordApp.Visible = chkMSWord.Checked; wordApp.WindowState = word.WdWindowState.wdWindowStateNormal; object missing = System.Reflection.Missing.Value; object readOnly = false; object isVisible = true; word.Document doc = wordApp.Documents.Open(ref strFileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); // Activate the document so it shows up in front doc.Activate(); SearchReplace("#1", cmboClass.Text, wordApp); SearchReplace("#2", cmboProfessor.Text, wordApp); SearchReplace("#3", cmboStudentName.Text, wordApp); SearchReplace("#4", cmboHomework.Text, wordApp); //This magic lets me use the checkbox name as the ms word field name //You can just add a checkbox to the form and a spot on the template //and it will automatically detect it with no code changes. foreach (var chkBox in Utility.GetAllChildren(this).OfType <CheckBox>()) { if (chkBox.Checked && chkBox != chkMSWord) { string newText = chkBox.Text; if (chkBox.Text == "Late submission") { newText += " " + txtDaysLate.Text + " days"; } SearchReplace(magicspace + chkBox.Text, magicx + newText, wordApp); } } //insert the comments at the end. wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing); wordApp.Selection.TypeText("\r\n\r\nComments: " + txtComments.Text); doc.Save(); //Merge to one doc if (chkSingleFile.Checked) { doc.Close(); object masterFile = txtPath.Text + "\\" + cmboClass.Text + " - " + cmboHomework.Text + ".doc"; if (!File.Exists((string)masterFile)) { File.Copy((string)strFileName, (string)masterFile); } else { word.Document d = wordApp.Documents.Open(ref masterFile, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); word.Selection selection = wordApp.Selection; //should put this in function. //Go to end of page. Object toWhat = word.WdGoToItem.wdGoToLine; Object toWhich = word.WdGoToDirection.wdGoToLast; wordApp.Selection.GoTo(toWhat, toWhich, ref missing, ref missing); wordApp.Selection.EndKey(word.WdUnits.wdStory, ref missing); object pageBreak = word.WdBreakType.wdPageBreak; selection.InsertBreak(ref pageBreak); selection.InsertFile((string)strFileName); d.Save(); if (!chkMSWord.Checked) { d.Close(); } } } //leave it open for inspection if chosen if (!chkMSWord.Checked) { if (!chkSingleFile.Checked) { doc.Close(); } wordApp.Quit(); } } btnSave.Enabled = true; btnSave.Text = "Save"; btnClear_Click(this, null); }