/// <summary> /// Attempts to run code cleanup on the specified document. /// </summary> /// <param name="document">The document for cleanup.</param> /// <param name="textBuffer">The text buffer for the document.</param> internal void Cleanup(Document document, ITextBuffer textBuffer) { if (!_codeCleanupAvailabilityLogic.ShouldCleanup(document, true)) return; // Make sure the document to be cleaned up is active, required for some commands like format document. document.Activate(); if (_package.IDE.ActiveDocument != document) { OutputWindowHelper.WriteLine(document.Name + " did not complete activation before cleaning started."); } _undoTransactionHelper.Run( delegate { _package.IDE.StatusBar.Text = String.Format("EditorConfig is cleaning '{0}'...", document.Name); // Perform the set of configured cleanups based on the language. RunCodeCleanupGeneric(document, textBuffer); _package.IDE.StatusBar.Text = String.Format("EditorConfig cleaned '{0}'.", document.Name); }, delegate(Exception ex) { OutputWindowHelper.WriteLine(String.Format("EditorConfig stopped cleaning '{0}': {1}", document.Name, ex)); _package.IDE.StatusBar.Text = String.Format("EditorConfig stopped cleaning '{0}'. See output window for more details.", document.Name); }); }
// Open a new document public void Open() { object missing = System.Reflection.Missing.Value; oDoc = oWordApplic.Application.Documents.Add(ref missing, ref missing, ref missing, ref missing); oDoc.Activate(); }
private void Open(string tempDoc) { object objTempDoc = tempDoc; object objMissing = System.Reflection.Missing.Value; objDocLast = objApp.Documents.Open( ref objTempDoc, //FileName ref objMissing, //ConfirmVersions ref objMissing, //ReadOnly ref objMissing, //AddToRecentFiles ref objMissing, //PasswordDocument ref objMissing, //PasswordTemplate ref objMissing, //Revert ref objMissing, //WritePasswordDocument ref objMissing, //WritePasswordTemplate ref objMissing, //Format ref objMissing, //Enconding ref objMissing, //Visible ref objMissing, //OpenAndRepair ref objMissing, //DocumentDirection ref objMissing, //NoEncodingDialog ref objMissing //XMLTransform ); objDocLast.Activate(); }
public override string Read(FileInfo fileInfo) { object nullobj = System.Reflection.Missing.Value; object readOnly = true; object noEncodingDialog = true; object confirmConversions = false; object visible = false; object filePath = fileInfo.FullName; object openAndRepair = false; object openFormat = WdOpenFormat.wdOpenFormatAuto; _wordDoc = WordApp.Documents.Open( ref filePath, ref confirmConversions, ref readOnly, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref openFormat, ref nullobj, ref visible, ref openAndRepair, ref nullobj, ref noEncodingDialog, ref nullobj); // Make this document the active document. _wordDoc.Activate(); string result = WordApp.ActiveDocument.Content.Text; _wordDoc.Close(ref nullobj, ref nullobj, ref nullobj); return result; }
// Open a file (the file must exists) and activate it public void Open(string strFileName) { object fileName = strFileName; object readOnly = false; object isVisible = true; object missing = System.Reflection.Missing.Value; oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing); oDoc.Activate(); }
public void Format(Document document, IDocumentFilter filter) { var currentDoc = dte.ActiveDocument; document.Activate(); if (dte.ActiveWindow.Kind == "Document") { if (filter.IsAllowed(document)) dte.ExecuteCommand(cmd.Command, cmd.Arguments); } currentDoc.Activate(); }
/// <summary> ///This method creates ms-word from template. /// </summary> public static void CreateMsWordFromTemplate() { try { if (_msWord == null) { _msWord = new Word.Application(); } // add blank documnet in word application if (_template == null) { return; } _doc = _msWord.Documents.Open(ref _template, ref _objMiss, ref _objMiss, ref _objMiss, ref _objMiss); _doc.Activate(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Formats and re-saves a document. /// </summary> /// <param name="doc">The document to format.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="doc" /> is <see langword="null" />. /// </exception> public static void FormatDocument(Document doc) { if (doc == null) { throw new ArgumentNullException("doc"); } // You can only format the active document, so we have to temporarily // activate each document that needs formatting. Document active = CodeRush.Documents.Active; if (doc != active) { doc.Activate(); } CodeRush.Documents.Format(); doc.Save(); if (doc != active) { active.Activate(); } }
public void OpenFile(string fileName) { try { var filePath = fileName.Replace('/','\\'); if (m_dte.get_IsOpenFile(EnvDTE.Constants.vsViewKindCode,filePath)) { Document doc = m_dte.Documents.Item(filePath); doc.Activate(); return; } Window window = null; if (m_dte.Solution != null) { var projItem = m_dte.Solution.FindProjectItem(filePath); if (projItem != null && !projItem.IsOpen) { window = projItem.Open(); } } //foreach (Window win in m_dte.Documents.Cast<Document>() // .FirstOrDefault(s => s.FullName == filePath).Windows) // win.Close(); if (window == null) { window = m_dte.ItemOperations.OpenFile(fileName,EnvDTE.Constants.vsViewKindCode); } if (window != null) { window.Visible = true; window.Activate(); } } catch (Exception) { return; } }
public DocumentBuilder(object template) { objMissing = System.Reflection.Missing.Value; object readOnly = false; word = new Application(); object objTempDoc = template; if (!File.Exists(template.ToString())) { doc = word.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing); // TODO office 2013 // doc.SaveAs2(template); doc.SaveAs(ref objTempDoc, 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); } else { doc = word.Documents.Open( ref objTempDoc, //FileName ref objMissing, //ConfirmVersions ref readOnly, //ReadOnly ref objMissing, //AddToRecentFiles ref objMissing, //PasswordDocument ref objMissing, //PasswordTemplate ref objMissing, //Revert ref objMissing, //WritePasswordDocument ref objMissing, //WritePasswordTemplate ref objMissing, //Format ref objMissing, //Enconding ref objMissing, //Visible ref objMissing, //OpenAndRepair ref objMissing, //DocumentDirection ref objMissing, //NoEncodingDialog ref objMissing //XMLTransform ); } doc.Activate(); GoToTheEnd(); }
public static TextDocument ActivateAndGetTextDocument(EnvDTE.Project prj, string strProjectItem) { ProjectItem pri = FindProjectItemByName(prj, strProjectItem); if (pri == null) { return(null); } // we need to ensure that the item is open since we would not // be able to get a text document otherwise if (!pri.get_IsOpen(EnvDTE.Constants.vsViewKindCode)) { pri.Open(EnvDTE.Constants.vsViewKindCode); } Document doc = pri.Document; doc.Activate(); TextDocument txdoc = doc.DTE.ActiveDocument.Object("TextDocument") as TextDocument; return(txdoc); }
/// <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 Boolean Convert(String inputFile, String outputFile) { try { Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); word.Visible = false; word.ScreenUpdating = false; object oMissing = System.Reflection.Missing.Value; Object filename = (Object)inputFile; 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); doc.Activate(); object outputFileName = (Object)outputFile; object fileFormat = WdSaveFormat.wdFormatPDF; 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); object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; return(true); } catch (Exception e) { //Console.WriteLine(e.Message); throw e; return(false); } }
private void go() { doc = app.Documents.Open(ref fileName, ref missing, ref readOnly, ref readOnly, ref missing, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Activate(); if (doc.Bookmarks.Exists("subject")) { object oBookMark = "subject"; doc.Bookmarks.get_Item(ref oBookMark).Range.Text = "Использование COM объектов"; } if (doc.Bookmarks.Exists("date")) { object oBookMark = "date"; doc.Bookmarks.get_Item(ref oBookMark).Range.Text = DateTime.Now.ToString("M/d/yyyy"); } if (doc.Bookmarks.Exists("discipline")) { object oBookMark = "discipline"; doc.Bookmarks.get_Item(ref oBookMark).Range.Text = "Проектированaие и архитектура программных систем"; } if (doc.Bookmarks.Exists("teachers")) { object oBookMark = "teachers"; doc.Bookmarks.get_Item(ref oBookMark).Range.Text = "Ужаринский А.Ю., Константинов И.С."; } app.Documents.Save(ref missing, ref missing); app.Application.Quit(ref missing, ref missing, ref missing); }
private void buttonWord_Click(object sender, EventArgs e) { if (!Directory.Exists(getPath(1))) //cria a pasta /pasta_temporaria/, em C. para utilizar, é necessário o "using System.IO;" { DirectoryInfo criapasta = Directory.CreateDirectory(getPath(1)); } if (File.Exists(getPath(2))) //checa se o arquivo já existe. para utilizar, é necessário o "using System.IO;" { MessageBox.Show("A listagem em Docx/PDF do banco de dados BDLivros já foi gerada na pasta 'C:/pasta_temporaria/'."); return; } Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); Document doc = word.Documents.Add(); Selection texto = word.Selection; doc.Activate(); LivroBLL.getProximo(); while (!Erro.getErro()) { texto.TypeText("Código: " + Livro.getCodigo() + "\nTítulo: " + Livro.getTitulo() + "\nAutor: " + Livro.getAutor() + "\nEditora: " + Livro.getEditora() + "\nAno: " + Livro.getAno()); texto.TypeParagraph(); texto.TypeText("---------------------------\n"); LivroBLL.getProximo(); } doc.SaveAs(getPath(2)); doc.SaveAs(getPath(3), WdSaveFormat.wdFormatPDF); word.Documents.Close(); word.Quit(); MessageBox.Show("Os dados do banco BDLivros foram salvos em .docx e .pdf, na pasta 'C:/pasta_temporaria/'."); }
protected Application OpenMsWordDocument(string inputFile) { object falseValue = false; object trueValue = true; object missing = Type.Missing; CloseWord(); _word = new Microsoft.Office.Interop.Word.Application(); _word.Visible = true; _word.Activate(); if (!string.IsNullOrEmpty(inputFile)) { object fileName = inputFile; _document = _word.Documents.Open(ref fileName, ref missing, ref falseValue, 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); _document.Activate(); } return(_word); }
void OpenFile(string fileName) { var filePath = fileName.Replace('/','\\'); if (m_dte.get_IsOpenFile(EnvDTE.Constants.vsViewKindCode,filePath)) { Document doc = m_dte.Documents.Item(filePath); doc.Activate(); return; } //foreach (Window win in m_dte.Documents.Cast<Document>() // .FirstOrDefault(s => s.FullName == filePath).Windows) // win.Close(); var window = m_dte.ItemOperations.OpenFile(fileName,EnvDTE.Constants.vsViewKindCode); if (window != null) { window.Visible = true; window.Activate(); } }
static void Main(string[] args) { var applicationWord = new Microsoft.Office.Interop.Word.Application(); applicationWord.Visible = true; Document dot = new Document(); try { dot = applicationWord.Documents.Open(@"path\to\your\a.dotx"); dot.Activate(); } catch (COMException ex) { Console.Write(ex); dot.Application.Quit(); } finally { dot?.Application?.Quit(); } }
public void Convert(string wordFileName, string pdfFileName) { _Word.Visible = false; _Word.ScreenUpdating = false; // Cast as Object for word Open method object filename = (object)wordFileName; // Use the dummy value as a placeholder for optional arguments Document doc = _Word.Documents.Open(ref filename, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue); doc.Activate(); //object outputFileName = pdfFileName = Path.ChangeExtension(wordFileName, "pdf"); object outputFileName = (object)pdfFileName; object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF Format doc.SaveAs(ref outputFileName, ref fileFormat, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref _MissingValue, ref _MissingValue); doc = null; // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)_Word).Quit(ref _MissingValue, ref _MissingValue, ref _MissingValue); _Word = null; //return outputFileName.ToString(); }
private void ConvretWordToPDF(string fileDocx) { Microsoft.Office.Interop.Word.Application Word = new Microsoft.Office.Interop.Word.Application(); object oMissing = System.Reflection.Missing.Value; FileInfo wordFile = new FileInfo(fileDocx); Word.Visible = false; Word.ScreenUpdating = false; 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); doc.Activate(); object outputFileName = wordFile.FullName.Replace(".docx", ".pdf"); object fileFormat = WdSaveFormat.wdFormatPDF; 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); object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; ((_Application)Word).Quit(ref oMissing, ref oMissing, ref oMissing); Word = null; }
/// <summary> /// Create new word object from template file /// </summary> /// <param name="fileName"></param> /// <param name="fileTemplate"></param> /// <returns></returns> public bool CreateObject(string fileName) { try { _fileName = fileName; WordApp = new ApplicationClass(); WordDocs = WordApp.Documents; cultureinfo = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); //2010.05.15 Khoan add start WordApp.ApplicationEvents2_Event_DocumentBeforeSave += new ApplicationEvents2_DocumentBeforeSaveEventHandler(WordApp_ApplicationEvents2_Event_DocumentBeforeSave); WordApp.ApplicationEvents2_Event_Quit += new ApplicationEvents2_QuitEventHandler(WordApp_ApplicationEvents2_Event_Quit); WordApp.ApplicationEvents2_Event_DocumentOpen += new ApplicationEvents2_DocumentOpenEventHandler(WordApp_ApplicationEvents2_Event_DocumentOpen); //WordApp.Visible = allowVisible; //2010.05.15 Khoan add end object _pathFile = (object)fileName; WordDoc = WordDocs.Open(ref _pathFile, ref fal, ref fal, ref fal, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref fal, ref oMissing, ref oMissing, ref oMissing, ref oMissing); if (allowVisible) { WordDoc.Activate(); } //CurrentSelection = WordDoc.Application.Selection; Thread.CurrentThread.CurrentCulture = cultureinfo; } catch (Exception) { Quit(false); return(false); } return(true); }
//public static void CloseWordFile(this Document doc, bool save = false) { doc.Close(save); } private static void FindAndReplace(this Document doc, object findText, object replaceWithText) { //options object matchCaseO = false; object matchWholeWordO = false; object matchWildCardsO = false; object matchSoundsLike = false; object matchAllWordForms = false; object forward = true; object format = false; object matchKashida = false; object matchDiacritics = false; object matchAlefHamza = false; object matchControl = false; object replace = 2; object wrap = 1; //execute find and replace doc.Activate(); App.Selection.Find.Execute(ref findText, ref matchCaseO, ref matchWholeWordO, ref matchWildCardsO, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl); }
private void FormatAllSelectedDocuments() { ItemsCollector itemsCollector = new ItemsCollector(); itemsCollector.CollectSelectedProjectItems(); List <Document> activeDocs = DocumentHandler.GetListOfActiveDocuments(); Document activeDocument = DocumentHandler.GetActiveDocument(); foreach (var item in itemsCollector.Items) { try { var projectItem = item.GetObject() as ProjectItem; mDocument = projectItem.Open().Document; ExecuteFormatCommand(); if (DocumentHandler.IsOpen(mDocument, activeDocs)) { mDocument.Save(); } else { mDocument.Close(vsSaveChanges.vsSaveChangesYes); } } catch (Exception) { } finally { mDocument = null; } } if (activeDocument != null) { activeDocument.Activate(); } }
public void Export(string notes) { try { Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application(); object missing = System.Reflection.Missing.Value; object fileName = "normal.dot"; object newTemplate = false; object docType = 0; object isVisible = true; Document aDoc = WordApp.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible); WordApp.Visible = true; aDoc.Activate(); WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; WordApp.Selection.Font.Bold = (int)Microsoft.Office.Interop.Word.WdConstants.wdToggle; WordApp.Selection.TypeText(notes); } catch { InformationBox.Show("Your document will be exported to your default text editor", "Microsoft Word not found"); File.WriteAllText("note_expot.txt", notes); Process.Start("note_expot.txt"); } }
private static List <ICommand> CollectCommands(Document template) { template.Activate(); WordRange searchRange = template.Range(); searchRange.Find.Text = "#<*>#"; searchRange.Find.MatchWildcards = true; searchRange.Find.MatchWholeWord = true; var results = new List <ICommand>(); while (searchRange.Find.Execute()) { var command = CreateCommand(searchRange.Duplicate); if (command != null) { results.Add(command); } } return(results); }
/// <summary> /// Merges changes from IRenameResult. /// </summary> /// <param name="renameResult">IRenameResult provider.</param> /// <param name="openAllChangedDocument">Indicates that open code files in Visual Studio Text Editor</param> /// <returns></returns> private void MergeChanges(IRenameResult renameResult, bool openAllChangedDocument) { if (renameResult == null) { throw new ArgumentNullException("renameResult"); } //Rename element and all refernces in other code files. if (renameResult is MultiRenameResult) { var multiRenameResult = renameResult as MultiRenameResult; Document currentWindow = DTE.ActiveDocument; foreach (var item in multiRenameResult) { if (item.Value.Success && item.Value.HasChanges) { if (openAllChangedDocument && !item.Key.get_IsOpen(Constants.vsViewKindCode)) { //Open code file in Visual Studio Text Editor DTE.ItemOperations.OpenFile(item.Key.get_FileNames(1), Constants.vsViewKindPrimary); } //Merge changed elements into code file from FileCodeModel. MergeChanges(GetFileCodeModel(item.Key), item.Value.ChangedElements, multiRenameResult.OldName); } } if (currentWindow != null) { currentWindow.Activate(); } } else if (renameResult is RenameResult) { //Rename element in actual code file. MergeChanges(GetFileCodeModel(), renameResult.ChangedElements, renameResult.OldName); } }
/// <summary> /// Formats and re-saves a document. /// </summary> /// <param name="doc">The document to format.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="doc" /> is <see langword="null" />. /// </exception> public static void FormatDocument(Document doc) { if (doc == null) { throw new ArgumentNullException("doc"); } // You can only format the active document, so we have to temporarily // activate each document that needs formatting. This is a limitation // because if the document is ALSO closing we can't make it active // so we can't format it. Document active = CodeRush.Documents.Active; if (doc != active) { doc.Activate(); } CodeRush.Documents.Format(); doc.Save(); if (doc != active) { active.Activate(); } }
private void generateIndexPage(byte[] templateLocation, WordInterface wordInterface, Document wordDocument, DataView riskDataRows) { lock (this.threadLock) { try { //Open the template String tempTemplateFile = Path.GetTempFileName(); File.WriteAllBytes(tempTemplateFile, templateLocation); Document indexPageTemplate = wordInterface.app.Documents.Open(tempTemplateFile); //Copy template to main document. wordInterface.copyDocumentToOtherDocument(indexPageTemplate, wordDocument, true); wordDocument.Activate(); //Find index table. Microsoft.Office.Interop.Word.Table indexTable = wordInterface.findTableWithTitle(wordDocument, "riskAssessmentIndex"); if (indexTable == null) { throw new Exception("Could not find riskAssessmentIndex table. Check your template."); } DataView minimalAdditionView = new DataView(this.tbl_MinimalAddition_In_RiskTableAdapter.GetData()); //Fill index table. foreach (DataRowView riskDataRow in riskDataRows) { int riskDataID = riskDataRow["ProjectRiskDataID"] != DBNull.Value ? (Int32)riskDataRow["ProjectRiskDataID"] : (Int32)riskDataRow["DefaultRiskDataID"]; Row newTableRow = indexTable.Rows.Add(ref missing); minimalAdditionView.RowFilter = string.Format("RiskDataID = '{0}'", riskDataID); newTableRow.Cells[2].Range.Text = riskDataRow["HazardSituation"].ToString(); newTableRow.Cells[3].Range.Text = riskDataRow["RiskID"].ToString(); //Insert a checkmark if it has remaining risk. if (minimalAdditionView.Count > 0) { newTableRow.Cells[4].Range.Font.Name = "Wingdings"; newTableRow.Cells[4].Range.Font.Size = 12; newTableRow.Cells[4].Range.Text = '\u00FC'.ToString(); } } //Add page numbers to index. int pageCount = wordDocument.ComputeStatistics(WdStatistic.wdStatisticPages, false); for (int i = 0; i < riskDataRows.Count; i++) { indexTable.Rows[2 + i].Cells[1].Range.Text = (i + pageCount).ToString(); } // Close and release the Document object. if (indexPageTemplate != null) { ((_Document)indexPageTemplate).Close(ref paramFalse, ref missing, ref missing); File.Delete(tempTemplateFile); indexPageTemplate = null; } } catch (Exception ex) { throw; } } }
static void Main(string[] args) { if (args.Length == 0) { DOCUMENT_NAME = "TEMPLATE.docx"; } else { DOCUMENT_NAME = args[0]; } Dictionary <string, Replacement> replacements = new Dictionary <string, Replacement>(); Dictionary <string, Replacement> blockReplacements = new Dictionary <string, Replacement>(); //Special replacements replacements.Add("{DATE}", new DateTimeReplacement()); replacements.Add("{TIME}", new DateTimeReplacement("h:mm tt")); replacements.Add("{DATETIME}", new DateTimeReplacement("MM/dd/yyyy h:mm tt")); //User-specified replacements + editing Application word = null; Document doc = null; try { word = new Application(); Console.WriteLine($"Opening document \"{DOCUMENT_NAME}\"..."); if (!File.Exists(DOCUMENT_NAME)) { Console.WriteLine("ERROR: Template does not exist at the specified location."); Console.ReadKey(); return; } doc = word.Documents.Open(Path.GetFullPath(DOCUMENT_NAME)); word.Visible = false; doc.Activate(); string text = doc.Range().Text; string blockText = ""; for (int i = 0; i < text.Length; i++) { if (blockText != "") { blockText += text[i]; } if (text[i] != '{') { continue; } i++; if (text[i] == '*' && text[i + 1] == '}') { i++; if (blockText != "") { Console.WriteLine($"Malformed block: {blockText}"); Console.WriteLine("Application will exit."); Console.ReadKey(); return; } blockText = "{*}"; } else if (text[i] == '/') { i++; blockText += "/}"; //First character already parsed if (!Regex.IsMatch(blockText, "{\\*[^}]")) { Console.WriteLine($"Malformed block: {blockText}"); Console.WriteLine("Application will exit."); Console.ReadKey(); return; } var fields = Regex.Matches(blockText, "{\\*[^}][^}]*}"); bool delete = true; foreach (Match m in fields) { if (replacements[m.Value].ToString() != "") { delete = false; } } if (delete) { blockReplacements.Add(blockText, EMPTY); } blockText = ""; } else //Replacement { string field = ""; while (text[i] != '}') { field += text[i]; i++; } string replace = field + '}'; field = '{' + field + '}'; if (!replacements.ContainsKey(field)) { Console.Write($"Text for field {field}: "); string answer = Console.ReadLine(); replacements.Add(field, new SimpleReplacement(answer)); } if (blockText != "") { blockText += replace; } } } foreach (string key in blockReplacements.Keys) { word.Selection.Find.Execute(FindText: key, ReplaceWith: blockReplacements[key].ToString(), Replace: WdReplace.wdReplaceAll); } foreach (string key in replacements.Keys) { word.Selection.Find.Execute(FindText: key, ReplaceWith: replacements[key].ToString(), Replace: WdReplace.wdReplaceAll); } word.Selection.Find.Execute(FindText: "{*}", ReplaceWith: "", Replace: WdReplace.wdReplaceAll); //Replace unused block indicators word.Selection.Find.Execute(FindText: "{/}", ReplaceWith: "", Replace: WdReplace.wdReplaceAll); while (doc.Range().Text.Contains(" ")) { word.Selection.Find.Execute(FindText: " ", ReplaceWith: " ", Replace: WdReplace.wdReplaceAll); } doc.SaveAs2(Path.Combine(Directory.GetCurrentDirectory(), $"Generated {DateTime.Now.ToString("yyMMdd.hh-mm-ss")}.docx")); } finally { doc?.Close(); word?.Quit(); } }
/// <summary> /// Attempts to select the text of the specified code item. /// </summary> /// <param name="document">The document.</param> /// <param name="codeItem">The code item.</param> internal static void SelectCodeItem(Document document, BaseCodeItem codeItem) { var textDocument = document.GetTextDocument(); if (textDocument == null) return; try { codeItem.RefreshCachedPositionAndName(); textDocument.Selection.MoveToPoint(codeItem.StartPoint, false); textDocument.Selection.MoveToPoint(codeItem.EndPoint, true); textDocument.Selection.SwapAnchor(); } catch (Exception) { // Select operation may fail if element is no longer available. } finally { // Always set focus within the code editor window. document.Activate(); } }
/// <summary> /// Attempts to move the cursor to the specified code item. /// </summary> /// <param name="document">The document.</param> /// <param name="codeItem">The code item.</param> /// <param name="centerOnWhole">True if the whole element should be used for centering.</param> internal static void MoveToCodeItem(Document document, BaseCodeItem codeItem, bool centerOnWhole) { var textDocument = document.GetTextDocument(); if (textDocument == null) return; try { object viewRangeEnd = null; TextPoint navigatePoint = null; codeItem.RefreshCachedPositionAndName(); textDocument.Selection.MoveToPoint(codeItem.StartPoint, false); if (centerOnWhole) { viewRangeEnd = codeItem.EndPoint; } var codeItemElement = codeItem as BaseCodeItemElement; if (codeItemElement != null) { navigatePoint = codeItemElement.CodeElement.GetStartPoint(vsCMPart.vsCMPartNavigate); } textDocument.Selection.AnchorPoint.TryToShow(vsPaneShowHow.vsPaneShowCentered, viewRangeEnd); if (navigatePoint != null) { textDocument.Selection.MoveToPoint(navigatePoint, false); } else { textDocument.Selection.FindText(codeItem.Name, (int)vsFindOptions.vsFindOptionsMatchInHiddenText); textDocument.Selection.MoveToPoint(textDocument.Selection.AnchorPoint, false); } } catch (Exception) { // Move operation may fail if element is no longer available. } finally { // Always set focus within the code editor window. document.Activate(); } }
/// <summary> /// Parses a given source file using cl.exe with the /showIncludes option and adds the output to the original graph. /// </summary> /// <remarks> /// If this is the first file, the graph is necessarily a tree after this operation. /// </remarks> /// <returns>true if successful, false otherwise.</returns> public static async Task <bool> AddIncludesRecursively_ShowIncludesCompilation(this IncludeGraph graph, Document document, OnCompleteCallback onCompleted) { var canPerformShowIncludeCompilation = await CanPerformShowIncludeCompilation(document); if (!canPerformShowIncludeCompilation.Result) { await Output.Instance.ErrorMsg(canPerformShowIncludeCompilation.Reason); return(false); } try { var dte = VSUtils.GetDTE(); if (dte == null) { await Output.Instance.ErrorMsg("Failed to acquire dte object."); return(false); } try { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); showIncludeSettingBefore = VSUtils.VCUtils.GetCompilerSetting_ShowIncludes(document.ProjectItem?.ContainingProject); VSUtils.VCUtils.SetCompilerSetting_ShowIncludes(document.ProjectItem?.ContainingProject, true); } catch (VCQueryFailure queryFailure) { await Output.Instance.ErrorMsg("Can't compile with show includes: {0}.", queryFailure.Message); return(false); } // Only after we're through all early out error cases, set static compilation infos. dte.Events.BuildEvents.OnBuildDone += OnBuildConfigFinished; CompilationBasedGraphParser.onCompleted = onCompleted; CompilationBasedGraphParser.documentBeingCompiled = document; CompilationBasedGraphParser.graphBeingExtended = graph; // Even with having the config changed and having compile force==true, we still need to make a dummy change in order to enforce recompilation of this file. { document.Activate(); var documentTextView = VSUtils.GetCurrentTextViewHost(); var textBuffer = documentTextView.TextView.TextBuffer; using (var edit = textBuffer.CreateEdit()) { edit.Insert(0, " "); edit.Apply(); } using (var edit = textBuffer.CreateEdit()) { edit.Replace(new Microsoft.VisualStudio.Text.Span(0, 1), ""); edit.Apply(); } } await VSUtils.VCUtils.CompileSingleFile(document); } catch (Exception e) { await ResetPendingCompilationInfo(); await Output.Instance.ErrorMsg("Compilation of file '{0}' with /showIncludes failed: {1}.", document.FullName, e); return(false); } return(true); }
/// <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"]; Application word = null; object oMissing = System.Reflection.Missing.Value; 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; Options wdOptions = null; Documents documents = null; 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) { 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 (IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword)) { normalTemplate.Saved = true; Console.WriteLine("Unable to open password protected file"); return((int)ExitCode.PasswordFailure); } // If we are opening a document with a write password and no read password, and // we are not in read only mode, we should follow the document properties and // enforce a read only open. If we do not, Word pops up a dialog if (!nowrite && String.IsNullOrEmpty(writePassword) && IsReadOnlyEnforced(inputFile)) { nowrite = true; } // Having signatures means we should open the document very carefully if (hasSignatures) { nowrite = true; autosave = false; openAndRepair = false; } 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); 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 (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 { Window docWin = null; 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 { word.PrintPreview = false; docWinView.RevisionsView = WdRevisionsView.wdRevisionsViewFinal; docWinView.ShowRevisionsAndComments = false; docWinView.ShowComments = false; docWinView.ShowFormatChanges = false; docWinView.ShowInkAnnotations = false; docWinView.ShowInsertionsAndDeletions = false; } catch (SystemException e) { Console.WriteLine("Failed to set revision settings {0}", e.Message); } // 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; if ((Boolean)options["word_fix_table_columns"]) { FixWordTableColumnWidths(doc); } } 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; 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"]; } 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; ReleaseCOMObject(docWinView); ReleaseCOMObject(docWin); } // Set up a delegate function if we're using a printer PrintDocument printFunc = delegate(string destination, string printerName) { word.ActivePrinter = printerName; doc.PrintOut(Background: false, OutputFileName: destination); }; if (String.IsNullOrEmpty((string)options["printer"])) { // No printer given, so export try { doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false, quality, WdExportRange.wdExportAllDocument, 1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa); } catch (Exception) { // Couldn't export, so see if there is a fallback printer if (!String.IsNullOrEmpty((string)options["fallback_printer"])) { PrintToGhostscript((string)options["fallback_printer"], outputFile, printFunc); } else { throw; } } } else { PrintToGhostscript((string)options["printer"], outputFile, printFunc); } 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); } ReleaseCOMObject(wdOptions); ReleaseCOMObject(documents); ReleaseCOMObject(doc); ReleaseCOMObject(tmpl); 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); } ReleaseCOMObject(word); } }
private void button1_Click(object sender, EventArgs e) { try { // Create a new Microsoft Word application object Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); // C# doesn't have optional arguments so we'll need a dummy value object oMissing = System.Reflection.Missing.Value; // Get list of Word files in specified directory DirectoryInfo dirInfo = new DirectoryInfo(txtFolder.Text); FileInfo[] wordFiles = dirInfo.GetFiles("*.doc*"); word.Visible = false; word.ScreenUpdating = false; foreach (FileInfo wordFile in wordFiles) { //object outputFileName = wordFile.FullName.Replace(".doc", ".pdf"); string extension = wordFile.FullName.Substring(wordFile.FullName.IndexOf(".")); object outputFileName = wordFile.FullName.Replace(extension, ".pdf"); if (!File.Exists(outputFileName.ToString())) { richTextBox1.AppendText("\nConverting file: " + outputFileName.ToString()); // Cast as Object for word Open method Object filename = (Object)wordFile.FullName; // Use the dummy value as a placeholder for optional arguments 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); doc.Activate(); object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF 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); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; // word has to be cast to type _Application so that it will find // the correct Quit method. ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); word = null; } else { richTextBox1.AppendText("\nFile exists: " + outputFileName.ToString()); } } } catch (Exception ex) { richTextBox1.AppendText("\n\nERROR: " + ex + "\n"); //throw; } }
public bool Open(string wordName, bool showApp) { bool result = false; if (string.IsNullOrEmpty(wordName)) return false; try { object fileName = wordName; object readOnly = false; object isVisible = true; object missing = Missing.Value; Document = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible); Document.Activate(); wordApp.Visible = showApp; result = true; } catch (Exception ex) { Quit(); throw new Exception(string.Format("Cannot open the file:{0}", wordName), ex); } return result; }
/// <summary> /// Attempts to run code cleanup on the specified document. /// </summary> /// <param name="document">The document for cleanup.</param> internal void Cleanup(Document document) { if (!_codeCleanupAvailabilityLogic.CanCleanupDocument(document, true)) return; // Make sure the document to be cleaned up is active, required for some commands like format document. document.Activate(); // Check for designer windows being active, which should not proceed with cleanup as the code isn't truly active. if (document.ActiveWindow.Caption.EndsWith(" [Design]")) { return; } if (_package.ActiveDocument != document) { OutputWindowHelper.WarningWriteLine($"Activation was not completed before cleaning began for '{document.Name}'"); } // Conditionally start cleanup with reorganization. if (Settings.Default.Reorganizing_RunAtStartOfCleanup) { _codeReorganizationManager.Reorganize(document); } new UndoTransactionHelper(_package, $"CodeMaid Cleanup for '{document.Name}'").Run( delegate { var cleanupMethod = FindCodeCleanupMethod(document); if (cleanupMethod != null) { OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup started for '{document.FullName}'"); _package.IDE.StatusBar.Text = $"CodeMaid is cleaning '{document.Name}'..."; // Perform the set of configured cleanups based on the language. cleanupMethod(document); _package.IDE.StatusBar.Text = $"CodeMaid cleaned '{document.Name}'."; OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup completed for '{document.FullName}'"); } }); }
/// <summary> /// Formats and re-saves a document. /// </summary> /// <param name="doc">The document to format.</param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="doc" /> is <see langword="null" />. /// </exception> public static void FormatDocument(Document doc) { if (doc == null) { throw new ArgumentNullException("doc"); } // You can only format the active document, so we have to temporarily // activate each document that needs formatting. Document active = CodeRush.Documents.Active; if (doc != active) { doc.Activate(); } CodeRush.Documents.Format(); doc.Save(); if (doc != active) { active.Activate(); } }
/// <summary> /// Called when a document is saved. /// </summary> /// <param name="document"> /// The document that was saved. /// </param> private void OnDocumentSaved(Document document) { if (this.docsInReformattingList.Remove(document)) { return; } Window previouslyShownWindow = null; try { this.docsInReformattingList.Add(document); previouslyShownWindow = this.dte.ActiveWindow; document.Activate(); this.dte.ExecuteCommand(ReSharperSilentCleanupCodeCommandName); if (!document.Saved) { document.Save(); } } finally { this.docsInReformattingList.Remove(document); if (previouslyShownWindow != null) { previouslyShownWindow.Activate(); } } }
//public async Task<ActionResult> Create(CandidateDTO candiadato , string Idioma) public async Task <string> Create(CandidateDTO candidato, string Idioma) { // capche google var response = HttpContext.Request.Form["g-recaptcha-response"]; string secretKey = "6LdhDmMUAAAAAOX9iW9kD9JbUIUqh-Ze68wxMwM1"; var client = new WebClient(); // get captcha verification result var verificationResultJson = client.DownloadString(string.Format ("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response)); // convert json to object var verificationResult = JsonConvert.DeserializeObject <ResponseCaptcha>(verificationResultJson); // process verification result if (!verificationResult.success) { return("KO"); } /* * // Los idiomas * ViewBag.idiomaSelecionado = Idioma == null ? "es-ES" : Idioma; * ViewBag.idiomas = new List<SelectListItem>(){ * new SelectListItem(){Text="Español",Value="es-ES",Selected=Idioma=="es-ES"}, * new SelectListItem(){Text="English",Value="en-GB",Selected=Idioma=="en-GB"} * }; * * // tengo que enviar el combo de las regiones: * var regiones = await _serviceRegion.Get(); * List<SelectListItem> listaRegion = new List<SelectListItem>(); * foreach (var item in regiones) * { * listaRegion.Add( * new SelectListItem() * { * Text = item.RegionName, * Value = item.Id.ToString() * }); * } * ViewBag.Title = "Portal Candidato"; * ViewBag.regiones = listaRegion; */ // para recoger el archivo var file = Request.Files["archivo"]; var fileName = file.FileName.Split('\\'); var nombre = fileName[fileName.Length - 1]; candidato.PathCV = fileName[fileName.Length - 1]; string value = System.Configuration.ConfigurationManager.AppSettings["tiposPermitidos"]; string pathCv = System.Configuration.ConfigurationManager.AppSettings["pathCv"]; var tiposPermitidos = value.Split(';'); var extension = Path.GetExtension(file.FileName); if (!tiposPermitidos.Contains(extension)) { return("KO"); } var fecha = DateTime.Now; var nombreCV = candidato.Email + "_" + fecha.ToString("yyyyMMddhhmmss") + fecha.Millisecond.ToString(); //string pathServer = Path.Combine(Server.MapPath("~/Repositorio/"), nombreCV + extension); string pathServer = pathCv + nombre; // configuramos el candidato candidato.RegionsIds = Request.Form["Regiones"]; candidato.PathCV = nombreCV + extension; candidato.TimeIn = fecha; candidato.User = "******"; try { //Copio en el servidor con el nombre original file.SaveAs(pathServer); if (extension == ".doc" || extension == ".docx") { Application word = new Application(); Document doc = word.Documents.Open(pathServer); doc.Activate(); doc.SaveAs2(pathCv + nombreCV + ".pdf", WdSaveFormat.wdFormatPDF); doc.Close(); } // si ya es PDF else { //Ruta de donde lo dejo file.SaveAs(pathCv + nombreCV + extension); } //Solo se guarda como pdf _serviceFile.moveFileToFtp(pathCv + nombreCV + ".pdf"); if (await _serviceCandidate.Insert(candidato)) { // return RedirectToAction("Create"); return("OK"); } return("KO"); } catch (Exception e) { // Delete the file after uploading if (System.IO.File.Exists(pathCv + extension)) { System.IO.File.Delete(pathCv + extension); } //ViewBag.error = "Se ha producido un error al guardar los datos. Vuelva a intentarlo"; return("KO excepcion"); } finally { // lo elimino del System.IO.File.Delete(pathServer); } }
private void generateRemainingRiskPages(byte[] headerTemplateLocation, byte[] templateLocation, WordInterface wordInterface, Document wordDocument, DataView riskDataRows, DataRow projectInfoRow) { lock (this.threadLock) { int currentRisk = 0; try { //Open template documents. String tempHeaderTemplateFile = Path.GetTempFileName(); String tempTemplateFile = Path.GetTempFileName(); File.WriteAllBytes(tempHeaderTemplateFile, headerTemplateLocation); File.WriteAllBytes(tempTemplateFile, templateLocation); Document remainingRiskHeaderTemplate = wordInterface.app.Documents.Open(tempHeaderTemplateFile); Document remainingRiskTemplate = wordInterface.app.Documents.Open(tempTemplateFile); foreach (DataRowView riskDataRow in riskDataRows) { //Set generating process backgroundWorker1.ReportProgress( 33 + (Int32)((float)currentRisk / (float)riskDataRows.Count * 33), (object)string.Format("Generating page {0} of {1}.", currentRisk + 1, riskDataRows.Count) ); currentRisk++; //Get the risk data id and set some variables. int riskDataID = (Int32)riskDataRow["RiskDataID"]; Color[] riskEstimationColors = { ARA_Colors.ARA_Green, ARA_Colors.ARA_Orange, ARA_Colors.ARA_Red }; //Get some more info about the risk. DataRow riskData = this.tbl_Risk_DataTableAdapter.GetData().FindByRiskDataID(riskDataID); DataView riskEstimationBeforeView = new DataView(this.get_RiskEstimation_In_RiskData_BeforeTableAdapter.GetData(riskDataID)); DataView riskEstimationAfterView = new DataView(this.get_RiskEstimation_In_RiskData_AfterTableAdapter.GetData(riskDataID)); DataView appliedRiskReductionMeasures = new DataView(this.get_RiskReduction_In_RiskDataTableAdapter.GetData(riskDataID)); DataView minimalAdditionMeasures = new DataView(this.get_MinimalAddition_In_RiskDataTableAdapter.GetData(riskDataID)); //Set some value's before copying document. remainingRiskTemplate.Activate(); foreach (DataRow exposedPersonRow in this.get_ExposedPersons_In_RiskDataTableAdapter.GetData(riskDataID).Rows) { ContentControls personCheckbox = remainingRiskTemplate.SelectContentControlsByTitle(exposedPersonRow["PersonDescription"].ToString()); if (personCheckbox.Count > 0) { personCheckbox[(object)1].Checked = exposedPersonRow["InProject"].ToString() == "1"; } } //Copy template. if (currentRisk % 2 == 1) { wordInterface.copyDocumentToOtherDocument(remainingRiskHeaderTemplate, wordDocument, false); wordInterface.copyDocumentToOtherDocument(remainingRiskTemplate, wordDocument, false); } else { wordInterface.copyDocumentToOtherDocument(remainingRiskTemplate, wordDocument, true); } wordDocument.Activate(); //Sets the risk hazard specifications. generateHazardIndentification(wordInterface, wordDocument, (Int32)riskData["DangerID"], (Int32)riskData["DangerSourceID"]); //Search and replace headerinfo. wordInterface.searchAndReplace(wordDocument, "<CustomerName>", projectInfoRow["Customer"].ToString()); wordInterface.searchAndReplace(wordDocument, "<MachineInfo>", string.Format("{0}/{1}", projectInfoRow["MachineNumber"].ToString(), projectInfoRow["OrderNumber"].ToString())); wordInterface.searchAndReplace(wordDocument, "<RiskID>", riskDataRow["RiskID"].ToString()); wordInterface.searchAndReplace(wordDocument, "<BriefActionDescription>", riskDataRow["HazardSituation"].ToString(), ARA_Colors.ARA_Red); //Search and replace riskdata. wordInterface.searchAndReplace(wordDocument, "<RiskGroup>", string.Format("{0} - {1}", riskDataRow["GroupName"].ToString(), riskDataRow["TypeName"].ToString())); wordInterface.searchAndReplace(wordDocument, "<ActionEvent>", riskData["HazardEvent"].ToString()); wordInterface.searchAndReplace(wordDocument, "<RiskReductionInfo>", riskData["RiskReductionInfo"].ToString()); wordInterface.searchAndReplace(wordDocument, "<MinimalAdditionInfo>", riskData["MinimalAdditionInfo"].ToString()); //Set the riskestimation fields. ARA_EditRiskRiskEstimation temp = new ARA_EditRiskRiskEstimation(); temp.setControlData(riskEstimationBeforeView); //Set risk class fields. riskEstimationBeforeView.RowFilter = "InProject = '1'"; if (riskEstimationBeforeView.Count != 4) { throw new Exception("Cant generate report, because risk " + riskDataID.ToString() + " isn't correctly filled in."); } wordInterface.searchAndReplace(wordDocument, "<RiskClassValueB>", temp.calculateRiskEstimationClass().ToString()); wordInterface.searchAndReplace(wordDocument, "<RiskClassDescriptionB>", ARA_Globals.RiskClassDescription[temp.calculateRiskEstimationClass()], riskEstimationColors[temp.calculateRiskEstimationClass()]); temp.setControlData(riskEstimationAfterView); riskEstimationAfterView.RowFilter = "InProject = '1'"; if (riskEstimationAfterView.Count != 4) { throw new Exception("Cant generate report, because risk " + riskDataID.ToString() + " isn't correctly filled in."); } wordInterface.searchAndReplace(wordDocument, "<RiskClassValueA>", temp.calculateRiskEstimationClass().ToString()); wordInterface.searchAndReplace(wordDocument, "<RiskClassDescriptionA>", ARA_Globals.RiskClassDescription[temp.calculateRiskEstimationClass()], riskEstimationColors[temp.calculateRiskEstimationClass()]); //Find minimal addition options table and fill it. Microsoft.Office.Interop.Word.Table minimalAdditionMeasuresTable = wordInterface.findTableWithTitle(wordDocument, "MinimalAdditionMeasures"); minimalAdditionMeasures.RowFilter = "InProject = '1'"; wordInterface.fillTableWithRiskReducingMeasures(wordDocument, minimalAdditionMeasuresTable, minimalAdditionMeasures, "MeasureSubGroup", "InProject"); minimalAdditionMeasuresTable.Title = ""; //Clear some memory. temp.Dispose(); temp = null; //Do we need to cancel execution? if (backgroundWorker1.CancellationPending) { break; } } //Remove template from memory. if (remainingRiskTemplate != null) { ((_Document)remainingRiskTemplate).Close(ref paramFalse, ref missing, ref missing); File.Delete(tempTemplateFile); remainingRiskTemplate = null; } //Remove headerTemplate from memory. if (remainingRiskHeaderTemplate != null) { ((_Document)remainingRiskHeaderTemplate).Close(ref paramFalse, ref missing, ref missing); File.Delete(tempHeaderTemplateFile); remainingRiskHeaderTemplate = null; } } catch (Exception ex) { } } }
public void createLendingForm(string fileName, string soPhieu, string ngayMuon, string maDG, string tenDG, string maThe) { word.Application winword = new Application(); winword.Visible = false; object misValue = System.Reflection.Missing.Value; object path = @"D:\NguyenNhutTan\DO_AN_QUAN_LY_THU_VIEN\LIBRARY MANAGEMENT\LIBRARY\Card\PMT.docx"; Document document = new Document(); document = winword.Documents.Open(path, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue); document.Activate(); foreach (FormField field in document.FormFields) { switch (field.Name) { case "sophieu": field.Range.Text = soPhieu; break; case "ngaymuon": field.Range.Text = ngayMuon; break; case "madg": field.Range.Text = maDG; break; case "tendg": field.Range.Text = tenDG; break; case "mathe": field.Range.Text = maThe; break; default: break; } } foreach (DataRow row in (new muonTra_BUS().getCTMTList(soPhieu).Rows)) { DataRow data = new sach_BUS().timkiem(row["MaSach"].ToString()).Rows[0]; Paragraph paragraph = document.Paragraphs.Add(ref misValue); paragraph.Range.Text = data["MaSach"].ToString() + "\t" + data["Ten"].ToString(); paragraph.Range.Font.Name = "Time News Roman"; paragraph.Range.Font.Size = 14; paragraph.Range.ListFormat.ApplyNumberDefault(ref misValue); paragraph.Range.InsertParagraphAfter(); } document.SaveAs2(fileName); document.Close(false, misValue, misValue); winword.Quit(); releaseObject(winword); releaseObject(document); System.Diagnostics.Process.Start(fileName); }
public static bool WordToPDF(string inFileName, string outFileName, out string errorString) { #region Declares errorString = string.Empty; Object oMissing = System.Reflection.Missing.Value; //null value Object oTrue = true; Object oFalse = false; Object oPageBreak = Word.WdBreakType.wdPageBreak; Object oOutputPath = outFileName; Object oSourcePath = inFileName; Object sectionStart = (Object)Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage; Word.Application oWord = null; #endregion try { oWord = new Word.Application(); //starts an instance of word oWord.Visible = false; //don't show the UI // Use the dummy value as a placeholder for optional arguments Document doc = oWord.Documents.Open(ref oSourcePath, 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); doc.Activate(); object fileFormat = WdSaveFormat.wdFormatPDF; // Save document into PDF Format doc.SaveAs( ref oOutputPath, 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); // Close the Word document, but leave the Word application open. // doc has to be cast to type _Document so that it will find the // correct Close method. object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; return(true); } catch (System.Exception ex) { errorString = ex.Message; Logger.LogMailMerge(false, "MailMergeWebApp:MailMerge() Error: " + Environment.NewLine + Environment.NewLine + ex.Message); } finally { //RELEASE WORD ITSELF oWord.Quit(ref oMissing, ref oMissing, ref oMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord); oWord = null; GC.Collect(); } return(false); }
/// <summary> /// Attempts to run code cleanup on the specified document. /// </summary> /// <param name="document">The document for cleanup.</param> /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param> internal void Cleanup(Document document, bool isAutoSave = false) { if (!_codeCleanupAvailabilityLogic.ShouldCleanup(document, true)) return; // Make sure the document to be cleaned up is active, required for some commands like // format document. document.Activate(); if (_package.ActiveDocument != document) { OutputWindowHelper.WarningWriteLine( string.Format("Activation was not completed before cleaning began for '{0}'", document.Name)); } // Conditionally start cleanup with reorganization. if (Settings.Default.Reorganizing_RunAtStartOfCleanup) { _codeReorderManager.Reorganize(document, isAutoSave); } _undoTransactionHelper.Run( () => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave), delegate { var cleanupMethod = FindCodeCleanupMethod(document); if (cleanupMethod != null) { OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeCleanupManager.Cleanup started for '{0}'", document.FullName)); _package.IDE.StatusBar.Text = string.Format("CodeMaid is cleaning '{0}'...", document.Name); // Perform the set of configured cleanups based on the language. cleanupMethod(document, isAutoSave); _package.IDE.StatusBar.Text = string.Format("CodeMaid cleaned '{0}'.", document.Name); OutputWindowHelper.DiagnosticWriteLine( string.Format("CodeCleanupManager.Cleanup completed for '{0}'", document.FullName)); } }, delegate(Exception ex) { OutputWindowHelper.ExceptionWriteLine( string.Format("Stopped cleaning '{0}'", document.Name), ex); _package.IDE.StatusBar.Text = string.Format("CodeMaid stopped cleaning '{0}'. See output window for more details.", document.Name); }); }
/// <summary> /// Fired when the user navigates to this task in the list. /// </summary> /// <param name="e">Parameter is not used.</param> protected override void OnNavigate(System.EventArgs e) { Param.Ignore(e); if (this.Document != null && this.Document.Length > 0) { try { Document document = ProjectUtilities.GetCodeDocument(this.Document); if (document == null) { AlertDialog.Show( this.Core, null, Strings.CouldNotNavigateToFile, Strings.Title, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { document.Activate(); TextSelection selection = (TextSelection)document.DTE.ActiveDocument.Selection; try { selection.GotoLine(this.violation.LineNumber, true); VirtualPoint vp = selection.ActivePoint; vp.TryToShow(vsPaneShowHow.vsPaneShowCentered, 0); } catch (ArgumentException) { // This happens when the line number passed to GotoLine is beyond the end of the file, or is otherwise // invalid. This can happen if the user has modified the file after StyleCop was run, and then // click an item in the error list which now points to an invalid line number. } } } catch (System.Runtime.InteropServices.COMException) { AlertDialog.Show( this.Core, null, Strings.CouldNotNavigateToFile, Strings.Title, MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { AlertDialog.Show( this.Core, null, Strings.UnknownFile, Strings.Title, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Methode die het word document opslaat als PDF bestand. /// </summary> /// <param name="excelBestand">Bestand om te zetten</param> public void ConverteerBestand(FileInfo wordBestand) { //Volledig pad ophalen en opslaan als object voor word.Documents.Open methode Object filename = (Object)wordBestand.FullName; //Optionele argumenten opvullen met leeg object 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); doc.Activate(); object outputFileName = String.Format("{0}.pdf", wordBestand.FullName.Substring(0, wordBestand.FullName.LastIndexOf('.'))); object fileFormat = WdSaveFormat.wdFormatPDF; //Document opslaanals PDF 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); //Document sluiten maar word nog niet. //Doc moet naar _Document geconverteerd worden zodat de Close methode opgeroepen kan worden. if (doc != null) { object saveChanges = WdSaveOptions.wdDoNotSaveChanges; ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); doc = null; } }