private string saveDocumentAsHtml(Document doc) { string tempRoot = System.IO.Path.GetTempPath(); Path = tempRoot + @"\" + doc.Name + ".htm"; object oMissing = System.Reflection.Missing.Value; WdSaveFormat format = WdSaveFormat.wdFormatFilteredHTML; doc.Content.Copy(); Application wordApp = new Microsoft.Office.Interop.Word.Application(); Document tempDoc = wordApp.Documents.Add(); tempDoc.Content.Paste(); tempDoc.SaveAs(path, format, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); (tempDoc as _Document).Close(false); (wordApp as _Application).Quit(false); tempDoc = null; wordApp = null; return(path); }
public static void SaveWordDoc(string originFile, IEnumerable<KeyValuePair<string, string>> replaceList = null, string targetFile = null, WdSaveFormat format = WdSaveFormat.wdFormatDocumentDefault, MsoEncoding encoding = MsoEncoding.msoEncodingAutoDetect) { Word.Application ap = null; Word.Document doc = null; object missing = Type.Missing; bool success = true; replaceList = replaceList ?? new Dictionary<string, string>(); targetFile = targetFile ?? originFile; if(targetFile.LastIndexOf('.')>targetFile.LastIndexOf('/')||targetFile.LastIndexOf('.')>targetFile.LastIndexOf('\\')) targetFile=targetFile.Remove(targetFile.LastIndexOf('.')); try { ap = new Word.Application(); ap.DisplayAlerts = WdAlertLevel.wdAlertsNone; doc = ap.Documents.Open(originFile, ReadOnly: false, Visible: false); doc.Activate(); Selection sel = ap.Selection; if (sel == null) throw new Exception("Unable to acquire Selection...no writing to document done.."); switch (sel.Type) { case WdSelectionType.wdSelectionIP: replaceList.ToList().ForEach(p => sel.Find.Execute(FindText: p.Key, ReplaceWith: p.Value, Replace: WdReplace.wdReplaceAll)); break; default: throw new Exception("Selection type not handled; no writing done"); } sel.Paragraphs.LineUnitAfter = 0; sel.Paragraphs.LineUnitBefore = 0; sel.Paragraphs.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle; doc.SaveSubsetFonts = false; doc.SaveAs(targetFile, format, Encoding: encoding); } catch (Exception) { success = false; } finally { if (doc != null) { doc.Close(ref missing, ref missing, ref missing); Marshal.ReleaseComObject(doc); } if (ap != null) { ap.Quit(ref missing, ref missing, ref missing); Marshal.ReleaseComObject(ap); } if(!success) throw new Exception(); // Could be that the document is already open (/) or Word is in Memory(?) } }
public static string GetExtensionFromWdSaveFormat(WdSaveFormat saveFormat) { // returns the standard WdSaveFormat type based on the reportFormat string if (saveFormat == WdSaveFormat.wdFormatDocumentDefault) { return("docx"); } ; if (saveFormat == WdSaveFormat.wdFormatDocument) { return("doc"); } ; if (saveFormat == WdSaveFormat.wdFormatDocument97) { return("doc"); } ; if (saveFormat == WdSaveFormat.wdFormatRTF) { return("rtf"); } ; if (saveFormat == WdSaveFormat.wdFormatPDF) { return("pdf"); } ; // invalid saveFormat so return empty string return(""); }
private static void ConvertDocument( string openFile, WdOpenFormat openFormat, string saveFile, WdSaveFormat saveFormat, string exportFile, WdExportFormat exportFormat, Action <Document> format = null, bool isWordVisible = false) { Application word = null; try { word = new Application { Visible = isWordVisible }; Trace.WriteLine(Invariant($"Opening {openFile} as {openFormat}.")); word.Documents.Open(openFile, Format: openFormat); Document document = word.Documents[openFile]; format?.Invoke(document); Trace.WriteLine(Invariant($"Saving {saveFile} as {saveFormat}")); document.SaveAs2(saveFile, saveFormat); Trace.WriteLine(Invariant($"Exporting {exportFile} as {exportFormat}")); document.ExportAsFixedFormat(exportFile, exportFormat, CreateBookmarks: WdExportCreateBookmarks.wdExportCreateHeadingBookmarks, OptimizeFor: WdExportOptimizeFor.wdExportOptimizeForOnScreen); } finally { word?.Documents?.Close(); word?.Quit(); } }
private static void ConvertDocument( string inputFile, WdOpenFormat inputFormat, string outputFile, WdSaveFormat outputFormat, Action <Document> format = null, bool isWordVisible = false) { Application word = null; try { word = new Application { Visible = isWordVisible }; Trace.WriteLine(Invariant($"Opening {inputFile} as {inputFormat}.")); word.Documents.Open(inputFile, Format: inputFormat); Document document = word.Documents[inputFile]; format?.Invoke(document); Trace.WriteLine(Invariant($"Saving {outputFile} as {outputFormat}")); document.SaveAs2(outputFile, outputFormat); } finally { word?.Documents?.Close(); word?.Quit(); } }
public static void SaveAs(ref Application word, WdSaveFormat format, string fileName) { if (File.Exists(fileName)) { File.Delete(fileName); } word.ActiveDocument.SaveAs(fileName, format); }
public static byte[] ConvertWordDocument(string sourceFilePath, MSOfficeOutput outputFormat, int encoding = -1) { byte[] res = null; WdSaveFormat saveFormat = WdSaveFormat.wdFormatUnicodeText; string fileExtension = ".txt"; switch (outputFormat) { case MSOfficeOutput.html: saveFormat = WdSaveFormat.wdFormatFilteredHTML; fileExtension = ".html"; break; case MSOfficeOutput.txt: saveFormat = WdSaveFormat.wdFormatText; fileExtension = ".txt"; break; case MSOfficeOutput.rtf: saveFormat = WdSaveFormat.wdFormatRTF; fileExtension = ".rtf"; break; case MSOfficeOutput.pdf: saveFormat = WdSaveFormat.wdFormatPDF; fileExtension = ".pdf"; break; default: break; } var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + fileExtension); Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); try { app.DisplayAlerts = WdAlertLevel.wdAlertsNone; app.Documents.Open(sourceFilePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse); if (encoding == -1) { app.ActiveDocument.SaveAs2(tempFile, saveFormat); } else { //more detailed save used for unicode text also for slovenian encoding: 1250 and for polish: 1257 app.ActiveDocument.SaveAs2(tempFile, saveFormat, LockComments: false, Password: "", AddToRecentFiles: true, WritePassword: "", ReadOnlyRecommended: false, EmbedTrueTypeFonts: false, SaveNativePictureFormat: false, SaveFormsData: false, SaveAsAOCELetter: false, Encoding: encoding, InsertLineBreaks: false, AllowSubstitutions: false, LineEnding: WdLineEndingType.wdCRLF); } app.ActiveDocument.Close(); app.Quit(); app = null; res = File.ReadAllBytes(tempFile); } catch (Exception e) { res = null; } finally { if (File.Exists(tempFile)) { File.Delete(tempFile); } } app = null; return(res); }
public static void ConvertToPdf(string input, string filename, string output) { WdSaveFormat format = WdSaveFormat.wdFormatPDF; Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application(); Microsoft.Office.Interop.Word._Document oDoc = null; object oMissing = System.Reflection.Missing.Value; try { oWord.Visible = false; oWord.ScreenUpdating = false; object isVisible = true; object readOnly = true; object confirmConversions = false; object addToRecentFiles = false; object passwordDocument = "12345"; object oInput = input; object oOutput = output; object oFormat = WdOpenFormat.wdOpenFormatAuto; if (filename.EndsWith(".docx") || filename.EndsWith(".doc")) { oFormat = WdOpenFormat.wdOpenFormatAllWord; } oDoc = oWord.Documents.OpenNoRepairDialog(ref oInput, ref confirmConversions, ref readOnly, ref addToRecentFiles, ref passwordDocument, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oFormat, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Activate(); object oSaveFormat = format; oDoc.SaveAs2(ref oOutput, ref oSaveFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } finally { oWord.Quit(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oWord); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oDoc); // Release all Interop objects. if (oDoc != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc); } if (oWord != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); } oDoc = null; oWord = null; GC.Collect(); GC.WaitForPendingFinalizers(); } }
public void Print(string filepathandname) { WdSaveFormat format = WdSaveFormat.wdFormatPDF; // Create an instance of Word.exe _Application oWord = new Application { // Make this instance of word invisible (Can still see it in the taskmgr). Visible = false }; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = true; // Does not cause any word dialog to show up //object readOnly = false; // Causes a word object dialog to show at the end of the conversion object oInput = filepathandname; object oOutput = filepathandname.Substring(0, filepathandname.Length - 4) + "pdf"; object oFormat = format; object oPrintToFile = true; // Load a document into our instance of word.exe _Document oDoc = oWord.Documents.Open( ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Make this document the active document. oDoc.Activate(); // Save this document using Word //oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, // ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing // ); oWord.Visible = false; PrintDialog pDialog = new PrintDialog(); oWord.ActivePrinter = GlobalVariables.PDF_PRINTER; oDoc.PrintOut(ref oMissing, ref oMissing, ref oMissing, ref oOutput, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oPrintToFile, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.Close(SaveChanges: false); oDoc = null; }
public static void ConvertDocToHtml(string path, WdSaveFormat format) { DirectoryInfo dirInfo = new DirectoryInfo(path); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc"); if (wordFiles.Length == 0) { return; } object oMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); try { word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { Object filename = (Object)wordFile.FullName; Document doc = word.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); try { doc.Activate(); object outputFileName = wordFile.FullName.Replace(".doc", ".html"); object fileFormat = format; doc.SaveAs(ref outputFileName, ref fileFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); } finally { object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } } } finally { ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; } }
/// <summary> /// /// </summary> /// <param name="path">存储路径</param> /// <param name="strContent">内容</param> public void CreateWord(string path, string strContent) { MSWord.Application wordApp = new MSWord.Application();; //Word应用程序变量,接口引用类型 //MSWord Document类不是new出来的,是这样新建出来的 MSWord.Document wordDoc = wordApp.Documents.Add(Nothing, Nothing, Nothing, Nothing); //Word文档变量 if (File.Exists((string)path)) //使用file类删除旧的文件 { File.Delete((string)path); } //保存格式 WdSaveFormat format = MSWord.WdSaveFormat.wdFormatDocumentDefault; wordDoc.SaveAs2(path, format, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing); wordDoc.Close(Nothing, Nothing, Nothing); wordApp.Quit(Nothing, Nothing, Nothing); }
static void Main(string[] args) { ////// Application word = new Application(); Document doc = new Document(); object fileName = @"C:\temp\20.pdf"; // Define an object to pass to the API for missing parameters object missing = System.Type.Missing; doc = word.Documents.Open(ref fileName, 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); String read = string.Empty; List <string> data = new List <string>(); //var lines = doc.SaveAs2() WdSaveFormat format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument; fileName = @"C:\temp\21.doc"; doc.SaveAs2(fileName, format); /* * for (int i = 0; i < doc.Paragraphs.Count; i++) * { * string temp = doc.Paragraphs[i + 1].Range.Text.Trim(); * if (temp != string.Empty) * File.WriteAllText(@"C:\temp\" + i.ToString() + ".txt", temp); * } */ ((_Document)doc).Close(); ((_Application)word).Quit(); }
// Convert method public static void Convert(string input, string output, WdSaveFormat format) { // Create an instance of Word.exe _Application oWord = new Word.Application { // Make this instance of word invisible (Can still see it in the taskmgr). Visible = false }; // Interop requires objects. object oMissing = System.Reflection.Missing.Value; object isVisible = true; object readOnly = true; // Does not cause any word dialog to show up //object readOnly = false; // Causes a word object dialog to show at the end of the conversion object oInput = input; object oOutput = output; object oFormat = format; // Load a document into our instance of word.exe _Document oDoc = oWord.Documents.Open( ref oInput, ref oMissing, ref readOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref isVisible, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Make this document the active document. oDoc.Activate(); // Save this document using Word oDoc.SaveAs(ref oOutput, ref oFormat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing ); // Always close Word.exe. oWord.Quit(ref oMissing, ref oMissing, ref oMissing); }
/// <summary> /// Print the labels /// Copied and amended from https://stackoverflow.com/questions/18056117/miscrosoft-word-label-printing-utility-issue /// </summary> /// <param name="creditors">List of creditors</param> /// <exception cref=">ApplicationException">Thrown when a Word error occurs</exception> public void PrintLabels(List <Creditor> creditors) { Application wordApp; wordApp = new Application(); Document wordDoc = null; Object missing = System.Reflection.Missing.Value; try { wordDoc = wordApp.Documents.Add(); // This adds one page full of a table with space for 21 labels. See below if more pages are necessary // I don't know WHY we need 2 documents, but I can't get it to work with only one. var newDoc = wordApp.MailingLabel.CreateNewDocument(LABEL_TYPE, "", Type.Missing, false, Type.Missing, Type.Missing, Type.Missing); wordApp.Visible = false; // Close the empty, original document ((_Document)wordDoc).Close(false, missing, missing); var table = newDoc.Content.ConvertToTable().Tables[1]; int column = -1; int row = 1; // When row > n * 7, need to add new rows, because we have started a new page foreach (Creditor c in creditors) { column += 2; if (column > NUM_COLUMNS) { column = 1; row++; if (row > NUM_ROWS) { // After filling the first page, add a new row as required table.Rows.Add(); } } // Create an inner table in the cell, with the name in bold and the number right-justified var innertable = table.Cell(row, column).Range.ConvertToTable(); innertable.Columns[2].Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; innertable.Columns[1].Cells[1].SetWidth(NAME_COLUMN_WIDTH, WdRulerStyle.wdAdjustFirstColumn); innertable.Columns[1].Cells[1].Range.Text = c.Name; innertable.Columns[1].Cells[1].Range.Font.Bold = BOLD; innertable.Columns[1].Cells[1].Range.Font.Color = WdColor.wdColorBlack; innertable.Columns[1].Cells[1].Range.Font.Size = NAME_FONT_SIZE; innertable.Columns[2].Cells[1].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; innertable.Columns[2].Cells[1].Range.Text = c.LineNumber; innertable.Columns[2].Cells[1].Range.Font.Bold = UNBOLD; innertable.Columns[2].Cells[1].Range.Font.Color = WdColor.wdColorPink; innertable.Columns[2].Cells[1].Range.Font.Size = NUMBER_FONT_SIZE; // Add constants and text for optional data // reference and phone are never in CFS data, and are optional in the Centre Manager database innertable.Rows.Add(); Cell cell = innertable.Cell((row + 1), 1); cell.Range.Font.Bold = UNBOLD; cell.Range.Font.Color = WdColor.wdColorBlack; cell.Range.Font.Size = TEXT_FONT_SIZE; cell.Range.Text = "Ref. No.: " + c.Reference; innertable.Rows.Add(); cell = innertable.Cell((row + 2), 1); cell.Range.Text = "Tel. No.: " + c.Phone; } if (destType == DestinationType.Save || destType == DestinationType.Both) { // Save and close the document // It seems necessary to use a file name without an extension, if the format is specified WdSaveFormat format = (Path.GetExtension(saveFilePath) == ".docx") ? WdSaveFormat.wdFormatDocument : WdSaveFormat.wdFormatDocument97; string saveFile = Path.GetDirectoryName(saveFilePath) + "\\" + Path.GetFileNameWithoutExtension(saveFilePath); newDoc.SaveAs(saveFile, format, missing, missing, false, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); ((_Document)newDoc).Close(false, missing, missing); } if (destType == DestinationType.Print || destType == DestinationType.Both) { // Print the labels System.Windows.Forms.PrintDialog pDialog = new System.Windows.Forms.PrintDialog(); if (pDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { wordApp.ActivePrinter = pDialog.PrinterSettings.PrinterName; newDoc.PrintOut(); } ((_Document)newDoc).Close(false, missing, missing); } if (destType == DestinationType.Open) { // Don't close the document, the user is editting it wordApp.Visible = true; } } // Does not catch ApplicationException, allow it to be passed to the caller catch (System.Runtime.InteropServices.COMException eCOM) { throw new ApplicationException("Word document create failed", eCOM); } }
static void Main(string[] args) { WdSaveFormat toFormat = WdSaveFormat.wdFormatFlatXML; string toExt = ".xml"; List <string> fileNames = new List <string>(args); if (fileNames.Contains("--pdf", StringComparer.InvariantCultureIgnoreCase)) { toFormat = WdSaveFormat.wdFormatPDF; toExt = ".pdf"; } else if (fileNames.Contains("--rtf", StringComparer.InvariantCultureIgnoreCase)) { toFormat = WdSaveFormat.wdFormatRTF; toExt = ".rtf"; } else if (fileNames.Contains("--txt", StringComparer.InvariantCultureIgnoreCase)) { toFormat = WdSaveFormat.wdFormatUnicodeText; toExt = ".txt"; } // if files were passed convert them to full path (because the word app does not start in the current dir) fileNames = (from f in fileNames where File.Exists(f) let fo = new FileInfo(f) select fo.FullName).ToList(); if (fileNames.Count == 0) { // if no files passed in args iterate all doc files in the current directory DirectoryInfo d = new DirectoryInfo(Directory.GetCurrentDirectory()); fileNames = d.GetFiles("*.doc").Select(x => x.FullName).ToList(); // .doc also matched .docx } // create a new instance of the Word app. var app = new Application(); foreach (string fname in fileNames) { try { Console.Error.Write(fname); string newFileName = Regex.Replace(fname, "\\.[a-z0-9]+", "", RegexOptions.IgnoreCase) + toExt; if (!File.Exists(newFileName)) { Document d = app.Documents.Open(FileName: fname, ReadOnly: true); object fileFormat = toFormat; d.SaveAs2(FileName: newFileName, FileFormat: fileFormat); d.Close(WdSaveOptions.wdDoNotSaveChanges); } Console.Error.WriteLine(" --> {0}", newFileName); } catch (Exception ex) { Console.Error.WriteLine("-----------------------------------------"); Console.Error.WriteLine("*****************************************"); Console.Error.WriteLine("-----------------------------------------"); Console.Error.WriteLine(fname); Console.Error.WriteLine("Error processing file:"); Console.Error.WriteLine(ex); Console.Error.WriteLine("-----------------------------------------"); Console.Error.WriteLine("*****************************************"); Console.Error.WriteLine("-----------------------------------------"); } } // close the app app.Quit(WdSaveOptions.wdDoNotSaveChanges); }
/// <summary> /// Convert to docx or PDF by using "NetOffice - MS Office in .NET", which uses Word application internal /// without version limitations. /// Note: /// http://netoffice.codeplex.com/ /// You need to add NetOffice.dll and WordApi.dll "References". /// To avoid error CS1752: Interop type 'Application' cannot be embedded. Use the applicable interface instead, /// in your Project, expand the "References", find the NetOffice and WordApi reference. /// Right click it and select properties, and change "Embed Interop Types" to false. /// </summary> /// <param name="fromFilePath"></param> /// <param name="toFilePath"></param> /// <param name="format"></param> private static void ConvertFormatByNetOffice(string fromFilePath, string toFilePath, WdSaveFormat format) { Word.Application wordApplication = new Word.Application() { DisplayAlerts = WdAlertLevel.wdAlertsNone }; var currentDoc = wordApplication.Documents.Open(fromFilePath); //var currentDoc = wordApplication.Documents.Add(); //Range _range = currentDoc.Range(); //_range.Text = @"Celsius = \sqrt(x+y) + sin(5/9 \times (Fahrenheit – 23 (\delta)^2))"; //foreach( var ac in wordApplication.OMathAutoCorrect.Entries) //{ // if (_range.Text.Contains(ac.Name)) // { // _range.Text = _range.Text.Replace(ac.Name, ac.Value); // } //} //currentDoc.OMaths.Add(_range); //var oMaths = _range.OMaths[1]; //oMaths.BuildUp(); //currentDoc.SaveAs(@"d:\temp\test\test.html", WdSaveFormat.wdFormatHTML, Type.Missing, Type.Missing, false, Type.Missing, null, false); currentDoc.SaveAs(toFilePath, format); currentDoc.Close(); wordApplication.Quit(); }
public void SaveAs(string fileName = "", WdSaveFormat format = WdSaveFormat.wdFormatDocument) { this.document.SaveAs2(fileName, format); }
public void ConvertWordDocument(string fullFileName, WdSaveFormat format) { Word.Application wordApp = new Word.Application(); try { string wordFileNameNoExt = fullFileName.Remove(fullFileName.LastIndexOf(".")); wordApp.Visible = false; wordApp.WindowState = WdWindowState.wdWindowStateMinimize; wordApp.Documents.Open(fullFileName); bool oldWord = (WdSaveFormat)wordApp.ActiveDocument.SaveFormat == WdSaveFormat.wdFormatDocument97; if (oldWord) { LastWordFileName = fullFileName; } else if (format == WdSaveFormat.wdFormatDocumentDefault) { RemoveLastDocxFile(); LastWordFileName = fullFileName; return; } string fName = wordFileNameNoExt; int lastSlashIndex = fullFileName.LastIndexOf("\\"); string shortFileNameNoExt = wordFileNameNoExt.Substring(lastSlashIndex); switch (format) { case WdSaveFormat.wdFormatDocumentDefault: RemoveLastDocxFile(); fName = Environment.CurrentDirectory + _tempDir + shortFileNameNoExt + ".docx"; LastConvertedWordFileName = fName; break; case WdSaveFormat.wdFormatDocument97: fName = LastWordFileName; break; case WdSaveFormat.wdFormatXPS: RemoveLastXpsFile(); fName = Environment.CurrentDirectory + _tempDir + shortFileNameNoExt + ".xps"; LastXpsFileName = fName; break; default: return; } wordApp.ActiveDocument.SaveAs(fName, format); if (format == WdSaveFormat.wdFormatXPS) { XpsDocument = new XpsDocument(LastXpsFileName, FileAccess.Read); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Failed to prepare MS Office Word document", MessageBoxButton.OK, MessageBoxImage.Stop); } finally { wordApp.Documents.Close(); wordApp.Quit(WdSaveOptions.wdDoNotSaveChanges); Marshal.ReleaseComObject(wordApp.Documents); Marshal.ReleaseComObject(wordApp); wordApp = null; } }
public void SaveAs(string fileName, WdSaveFormat format) { _document.GetType() .InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, _document, new object[] { fileName, format }); }
public void SaveAs(string fileName, WdSaveFormat format) { _document.GetType() .InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, _document, new object[] {fileName, format}); }