Beispiel #1
0
        public void SaveAs(string strFileName)
        {
            object fileName = strFileName;

            oDoc.SaveAs(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);
        }
Beispiel #2
0
 /// <summary>
 /// Copies a document to a specified path.
 /// </summary>
 /// <param name="document">The Document instance.</param>
 /// <param name="path">The path where the new file will be saved.</param>
 /// <param name="saveFormat">The save format.</param>
 /// <exception cref="IOException">When the file cannot be saved.</exception>
 /// <remarks>The document is saved in Unicode little endian encoding.</remarks>
 /// <returns>True if the operation succedes. False otherwise.</returns>
 public bool ShadowCopyDocument(Word.Document document, string path, Word.WdSaveFormat saveFormat)
 {
     try
     {
         Object format               = saveFormat;
         Object copyPath             = path;
         Object encoding             = MsoEncoding.msoEncodingUTF8;
         Object missing              = Type.Missing;
         Object originalFilePath     = document.FullName;
         Object initialDocSaveFormat = document.SaveFormat;
         document.SaveAs(ref copyPath, ref format, ref missing, ref missing, ref missing, ref missing,
                         ref missing, ref missing, ref missing, ref missing, ref missing, ref encoding,
                         ref missing, ref missing, ref missing, ref missing);
         //Refresh the active instance(required after acquiring chart data from Excel)
         document = addin.Application.ActiveWindow.Document;
         document.SaveAs(ref originalFilePath, ref initialDocSaveFormat, 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);
     }
     catch (IOException ioex)
     {
         Log.Exception(ioex);
         UserNotifier.Error(ioex.Message);
         return(false);
     }
     catch (Exception ex)
     {
         Log.Exception(ex);
         return(false);
     }
     return(true);
 }
Beispiel #3
0
        public void SaveAs(string strFileName)
        {
            object missing  = System.Reflection.Missing.Value;
            object fileName = strFileName;

            oDoc.SaveAs(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);
        }
Beispiel #4
0
        private void button3_Click(object sender, EventArgs e)
        {
            X509Certificate cert = new X509Certificate(textBox1.Text);
            string          ogrn = cert.Subject.Substring(cert.Subject.IndexOf("OGRN=") + 5, 13);

            Context db        = new Context();
            var     uchastnik = db.Uchastniki_SMEV.FirstOrDefault(p => p.OGRN == ogrn);

            Word._Application oWord = new Word.Application();
            Word.Document     oDoc  = oWord.Documents.Add(Environment.CurrentDirectory + "\\Заявка на перерегистрацию ЭП.dotx");
            oDoc.Bookmarks["Namespace"].Range.Text = "Продуктивная среда";
            oDoc.Bookmarks["FullName"].Range.Text  = uchastnik.Polnoe_naimenovanie_Uchastnika;
            oDoc.Bookmarks["ShortName"].Range.Text = uchastnik.Kratkoe_naimenovanie_Uchastnika;
            oDoc.Bookmarks["OGRN"].Range.Text      = uchastnik.OGRN;
            if (uchastnik.Tip_Uchastnika == 1)
            {
                oDoc.Bookmarks["Type"].Range.Text = "ОМСУ";
            }
            else
            {
                oDoc.Bookmarks["Type"].Range.Text = "РОИВ";
            }
            oDoc.Bookmarks["Mnemonic"].Range.Text    = uchastnik.Mnemonika_Uchastnika_v_SMEV3;
            oDoc.Bookmarks["FullNameIS"].Range.Text  = uchastnik.Polnoe_naimenovanie_IS;
            oDoc.Bookmarks["ShortNameIS"].Range.Text = uchastnik.Kratkoe_naimenovanie_IS;
            oDoc.Bookmarks["MnemonicIS"].Range.Text  = uchastnik.Mnemonika_IS_v_SMEV3;
            oDoc.SaveAs(FileName: textBox2.Text + $"\\Заявка на перерегистрацию ЭП ОВ {uchastnik.Polnoe_naimenovanie_IS} прод.docx");
            oDoc.Close();

            oDoc = oWord.Documents.Add(Environment.CurrentDirectory + "\\Заявка на перерегистрацию ЭП.dotx");
            oDoc.Bookmarks["Namespace"].Range.Text = "Тестовая среда";
            oDoc.Bookmarks["FullName"].Range.Text  = uchastnik.Polnoe_naimenovanie_Uchastnika;
            oDoc.Bookmarks["ShortName"].Range.Text = uchastnik.Kratkoe_naimenovanie_Uchastnika;
            oDoc.Bookmarks["OGRN"].Range.Text      = uchastnik.OGRN;
            if (uchastnik.Tip_Uchastnika == 1)
            {
                oDoc.Bookmarks["Type"].Range.Text = "ОМСУ";
            }
            else
            {
                oDoc.Bookmarks["Type"].Range.Text = "РОИВ";
            }
            oDoc.Bookmarks["Mnemonic"].Range.Text    = uchastnik.Mnemonika_Uchastnika_v_SMEV3;
            oDoc.Bookmarks["FullNameIS"].Range.Text  = uchastnik.Polnoe_naimenovanie_IS;
            oDoc.Bookmarks["ShortNameIS"].Range.Text = uchastnik.Kratkoe_naimenovanie_IS;
            string mnemonicIS = uchastnik.Mnemonika_IS_v_SMEV3;

            if (uchastnik.Mnemonika_IS_v_SMEV3[uchastnik.Mnemonika_IS_v_SMEV3.Length - 1] == 'S')
            {
                mnemonicIS = mnemonicIS.Replace('S', 'T');
            }
            oDoc.Bookmarks["MnemonicIS"].Range.Text = mnemonicIS;
            oDoc.SaveAs(FileName: textBox2.Text + $"\\Заявка на перерегистрацию ЭП ОВ {uchastnik.Polnoe_naimenovanie_IS} тест.docx");;
            oDoc.Close();

            toolStripStatusLabel1.Text = "";
            toolStripStatusLabel1.Text = "Готово";
        }
Beispiel #5
0
        /// <summary>
        /// 保存为...
        /// </summary>
        /// <param name="fileName">文件名(包含路径)</param>
        public void SaveAs(string fileName)
        {
            if (_wordDocument == null)
            {
                _wordDocument = _wordApplication.ActiveDocument;
            }
            object objFileName = fileName;

            _wordDocument.SaveAs(ref objFileName, 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);
        }
        private void SaveOffice2003(FileInfo file)
        {
            DirectoryInfo dir = file.Directory;

            dir.Create();
            object fileNameDOC  = file.FullName;
            object objformatDoc = Word.WdSaveFormat.wdFormatDocument;

            if (file.Exists)
            {
                file.Delete();
            }
            document.SaveAs(ref fileNameDOC, ref objformatDoc, ref missing, ref missing, ref objfalse, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
        }
Beispiel #7
0
        public void SaveAs(string strFileName)
        {
            try
            {
                object missing  = System.Reflection.Missing.Value;
                object fileName = strFileName;

                oDoc.SaveAs(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);
            }
            catch (Exception ex)
            {
                CreateLogTxt.ErrWriter(ex);
            }
        }
Beispiel #8
0
        public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
        {
            object fileName = strFileName;

            if (File.Exists(strFileName))
            {
                oDoc.SaveAs(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);
            }
            else
            {
                oDoc.SaveAs(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);
            }
        }
Beispiel #9
0
        private void convertirword()
        {
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            wordApp.Visible = false;


            object filename = @"C:\Users\raul\Documents\Visual Studio 2012\Projects\WorkFlow Seguros Futuro\WorkFlow Seguros Futuro\files\" + FileUpload.FileName; // input

            object newFileName = Server.MapPath("~/files/" + Path.GetFileNameWithoutExtension(FileUpload.FileName) + ".pdf");                                      // output
            object missing     = System.Type.Missing;

            Microsoft.Office.Interop.Word.Document doc = wordApp.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);

            object formatoArquivo = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;



            doc.SaveAs(ref newFileName, ref formatoArquivo, 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);

            doc.Close(ref missing, ref missing, ref missing);

            wordApp.Quit(ref missing, ref missing, ref missing);
        }
Beispiel #10
0
        public void SaveAsPDF()
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object oMissing = System.Reflection.Missing.Value;
            // Cast as Object for word Open method

            Object filename = (Object)_filename;

            Microsoft.Office.Interop.Word.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 = _filename.Replace(".docx", ".pdf");
            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);
            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;
        }
Beispiel #11
0
        //保存文件函数
        private void SaveFile(string name)
        {
            try
            {
                Word.Application myApp = new Word.Application();
                Word.Document    myDoc = myApp.Documents.Add(); //添加到打开文档集合中的新空文档
                myDoc.ActiveWindow.Selection.WholeStory();      //全选
                richTextBox1.SelectAll();
                richTextBox1.Copy();                            //复制数据到剪贴板


                myDoc.ActiveWindow.Selection.Paste();       //粘贴
                myDoc.ActiveWindow.Selection.WholeStory();
                myApp.Selection.Font.Color = WdColor.wdColorBlack;
                object myFileName = name;                   //string转化为object类型
                myDoc.SaveAs(ref myFileName);
                myDoc.Close();                              //关闭WordDoc文档对象
                myApp.Quit();                               //关闭WordApp组件对象
                MessageBox.Show("WORD文件保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }                                               //信息提示内容 对话框标题 显示确定按钮 显示感叹号图标
            catch (Exception ex)
            {
                MessageBox.Show("WORD文件保存失败!\n" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
 private void btn_New_Click(object sender, EventArgs e)
 {
     btn_New.Enabled = false;                     //停用新建按鈕
     ThreadPool.QueueUserWorkItem(                //使用線程池
         (P_temp) =>                              //使用lambda表達式
     {
         G_wa = new Word.Application();           //建立Word應用程式對像
         Word.Document P_wd = G_wa.Documents.Add( //建立新檔案檔
             ref G_missing, ref G_missing, ref G_missing, ref G_missing);
         Word.Range P_Range = P_wd.Paragraphs[1].Range;
         using (StreamReader P_StreamReader =    //建立流讀取器對像
                                              new StreamReader(G_OpenFileDialog.FileName, Encoding.Default))
         {
             P_Range.Text = P_StreamReader.ReadToEnd();
         }
         G_str_path = string.Format(    //計算檔案儲存路徑
             @"{0}\{1}", G_FolderBrowserDialog.SelectedPath,
             DateTime.Now.ToString("yyyy年M月d日h時s分m秒fff毫秒") + ".doc");
         P_wd.SaveAs(    //儲存Word檔案
             ref G_str_path,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing);
         ((Word._Application)G_wa.Application).Quit( //退出應用程式
             ref G_missing, ref G_missing, ref G_missing);
         this.Invoke(                                //開始執行視窗線程
             (MethodInvoker)(() =>                   //使用lambda表達式
         {
             btn_Display.Enabled = true;             //啟用顯示按鈕
             MessageBox.Show("成功建立Word檔案檔!", "提示!"); //彈出消息對話框
         }));
     });
 }
Beispiel #13
0
        private object G_str_path;                         //定义文件保存路径字段

        private void btn_New_Click(object sender, EventArgs e)
        {
            btn_New.Enabled = false;                                                  //将新建按钮设置为不可用
            ThreadPool.QueueUserWorkItem(                                             //开始线程池
                (pp) =>                                                               //使用lambda表达式
            {
                G_wa               = new Microsoft.Office.Interop.Word.Application(); //创建应用程序对象
                object P_obj       = "Normal.dot";                                    //定义文档模板
                Word.Document P_wd = G_wa.Documents.Add(                              //向Word应用程序中添加文档
                    ref P_obj, ref G_missing, ref G_missing, ref G_missing);
                G_str_path = string.Format(                                           //计算文件保存路径
                    @"{0}\{1}", G_FolderBrowserDialog.SelectedPath,
                    DateTime.Now.ToString("yyyy年M月d日h时s分m秒fff毫秒") + ".doc");
                P_wd.SaveAs(    //保存Word文件
                    ref G_str_path,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing);
                ((Word._Application)G_wa.Application).Quit( //退出应用程序
                    ref G_missing, ref G_missing, ref G_missing);
                this.Invoke(                                //调用窗体线程
                    (MethodInvoker)(() =>                   //使用lambda表达式
                {
                    MessageBox.Show(                        //提示已经创建Word
                        "成功创建Word文档!", "提示!");
                    btn_display.Enabled = true;             //启用显示按钮
                }));
            });
        }
Beispiel #14
0
        private void generateSemesterTitle()
        {
            String path = Environment.CurrentDirectory + "\\SemesterTitle.dotx";

            Word.Application app = new Word.Application();
            // Создаём объект документа
            Word.Document doc = app.Documents.Add(path);
            doc.Activate();

            doc.Bookmarks["NAME"].Range.Text            = textName.Text;
            doc.Bookmarks["DIRECTION"].Range.Text       = textCathedra.Text;
            doc.Bookmarks["FACULTY"].Range.Text         = textFaculty.Text;
            doc.Bookmarks["GROUP"].Range.Text           = textGroup.Text;
            doc.Bookmarks["PROFESSOR"].Range.Text       = textProfessor.Text;
            doc.Bookmarks["SUBJECT"].Range.Text         = textSubject.Text;
            doc.Bookmarks["SUBJECT_LESSONS"].Range.Text = textDiscipline.Text;
            doc.Bookmarks["YEAR"].Range.Text            = numYear.Value.ToString();


            doc.SaveAs(FileName: Environment.CurrentDirectory + "\\" + textName.Text + "_" + textDiscipline.Text + ".docx");
            doc.Close();

            MessageBox.Show("Файл " + textName.Text + "_" + textDiscipline.Text + ".docx успешно сгенерирован!",
                            "Успех",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxOptions.DefaultDesktopOnly);
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="newFilePath"></param>
        /// <param name="newFileName"></param>
        /// <param name="saveFormat"></param>
        /// <returns></returns>
        private bool SaveFile(string newFilePath, ref string newFileName, int saveFormat = 16)
        {
            if (string.IsNullOrEmpty(newFileName))
            {
                newFileName = DateTime.Now.ToString("yyyyMMddHHmmss");

                switch (saveFormat)
                {
                case 0:    // Word.WdSaveFormat.wdFormatDocument
                    newFileName += ".doc";
                    break;

                case 16:    // Word.WdSaveFormat.wdFormatDocumentDefault
                    newFileName += ".docx";
                    break;

                case 17:    // Word.WdSaveFormat.wdFormatPDF
                    newFileName += ".pdf";
                    break;

                default:
                    break;
                }
            }

            object newfile      = Path.Combine(newFilePath, newFileName);
            object wdSaveFormat = saveFormat;

            wordDoc.SaveAs(ref newfile, ref wdSaveFormat);
            return(true);
        }
Beispiel #16
0
        /// <summary>
        ///  Convert the word document to xps document
        /// </summary>
        /// <param name="wordFilename">Word document Path</param>
        /// <param name="xpsFilename">Xps document Path</param>
        /// <returns></returns>
        public static XpsDocument ConvertWordToXps(string wordFilename, string xpsFilename)
        {
            // Create a WordApplication and host word document
            Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            try
            {
                wordApp.Documents.Open(wordFilename);

                // To Invisible the word document
                wordApp.Application.Visible = false;

                // Minimize the opened word document
                wordApp.WindowState = Word.WdWindowState.wdWindowStateMinimize;

                Word.Document doc = wordApp.ActiveDocument;
                doc.SaveAs(xpsFilename, Word.WdSaveFormat.wdFormatXPS);

                XpsDocument xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read);
                return(xpsDocument);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurs, The error message is  " + ex.ToString());
                return(null);
            }
            finally
            {
                wordApp.Documents.Close();
                ((Word._Application)wordApp).Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
            }
        }
Beispiel #17
0
 public void Convert(string openPath, string savePath)
 {
     Word.Document doc = null;
     try
     {
         doc = WordApp.Documents.Open(Path.GetFullPath(openPath));
     }
     catch
     {
         Console.WriteLine("Не смог открыть файл {0}", openPath);
         WordApp.Quit();
     }
     try
     {
         doc.SaveAs(FileName: Path.GetFullPath(savePath), FileFormat: Word.WdSaveFormat.wdFormatPDF);
         doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
     }
     catch
     {
         Console.WriteLine("Не смог сохранить файл {0}", savePath);
     }
     finally
     {
         if (WordApp.Documents != null)
         {
             WordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
         }
         WordApp.Quit();
     }
 }
Beispiel #18
0
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            bool result = false;

            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.Application    application  = null;

            Microsoft.Office.Interop.Word.Document document = null;
            object unknow = System.Type.Missing;

            application         = new Microsoft.Office.Interop.Word.Application();
            application.Visible = false;
            document            = application.Documents.Open(sourcePath);
            document.SaveAs();
            document.ExportAsFixedFormat(targetPath, exportFormat, false);
            //document.ExportAsFixedFormat(targetPath, exportFormat);
            result = true;

            //application.Documents.Close(ref unknow, ref unknow, ref unknow);
            document.Close(ref unknow, ref unknow, ref unknow);
            document = null;
            application.Quit();
            //application.Quit(ref unknow, ref unknow, ref unknow);
            application = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return(result);
        }
Beispiel #19
0
 public static void ConvertFromWord(string sourcePath, string targetPath)
 {
     Word.Application application = null;
     Word.Document    document    = null;
     try
     {
         application = new Microsoft.Office.Interop.Word.Application();
         application.Application.Visible = false;
         document = application.Documents.Open(sourcePath);
         document.SaveAs(targetPath, Word.WdSaveFormat.wdFormatPDF);
     }
     finally
     {
         if (document != null)
         {
             ((Word._Document)document).Close();
             document = null;
         }
         if (application != null)
         {
             ((Word._Application)application).Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
             application = null;
         }
     }
 }
        private void saveFileThread()
        {
            string text = "";

            wordApp = new MSWord.Application();
            readDoc = wordApp.Documents.Add(ref QS, ref QS, ref QS, ref QS);
            foreach (ListViewItem nowItem in this.listViewEx1.Items)
            {
                text += nowItem.SubItems[0].Text + ";";
            }
            text = text.TrimEnd(';');
            readDoc.Paragraphs[1].Range.Text = text;
            readDoc.SaveAs(ref chWordsPath, ref format, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
            readDoc.Close(ref QS, ref QS, ref QS);
            text    = "";
            readDoc = wordApp.Documents.Add(ref QS, ref QS, ref QS, ref QS);
            foreach (ListViewItem nowItem in this.listViewEx1.Items)
            {
                text += nowItem.SubItems[1].Text + ";";
            }
            text = text.TrimEnd(';');
            readDoc.Paragraphs[1].Range.Text = text;
            readDoc.SaveAs(ref keyWordsPath, ref format, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS, ref QS);
            readDoc.Close(ref QS, ref QS, ref QS);
            wordApp.Quit(MSWord.WdSaveOptions.wdDoNotSaveChanges, ref QS, ref QS);
        }
        /// <summary>
        /// Saves the document out with the appropriate new filename and format.
        /// Also does any special handling such as accepting/rejecting changes
        /// before saving.
        /// </summary>
        private void SaveDocument()
        {
            object missing          = System.Reflection.Missing.Value;
            object newFileName      = m_newFileName;
            object encoding         = Office_Core.MsoEncoding.msoEncodingUTF8;
            object addToRecentFiles = false;
            object ttfonts          = false;
            object linebreaks       = false;
            object formsdata        = false;
            object bidimarks        = false;

            // TODO: find out what this does.

            HandleTrackedChanges();
            HandleSmartTags();

            if (Word_Class.WdSaveFormat.wdFormatDocument == (Word_Class.WdSaveFormat)m_newFormatType)
            {
                m_wordDoc.ActiveWindow.View.Type = Word_Class.WdViewType.wdPrintView;
            }
            m_wordDoc.SaveAs(ref newFileName, ref m_newFormatType, ref missing,
                             ref missing, ref addToRecentFiles, ref missing, ref missing,
                             ref ttfonts, ref missing, ref formsdata, ref missing, ref encoding,
                             ref linebreaks, ref missing, ref missing, /*bidi marks!!*/ ref bidimarks);
        }
Beispiel #22
0
        private void SetFolderSuffix(XOfficeCommonSettings settings)
        {
            Object _false             = false;
            Object _true              = true;
            String defaultSuffixValue = "_files";

            Word.Document newDoc = Application.Documents.Add(ref missing, ref missing, ref missing, ref _false);

            String uniqueName = "XOffice" + DateTime.Now.Ticks.ToString();
            Object uniquePath = Path.Combine(settings.PagesRepository, uniqueName);

            //required by COM interop
            Object format = Word.WdSaveFormat.wdFormatHTML;

            newDoc.SaveAs(ref uniquePath, ref format, ref missing, ref missing, ref _false, ref missing, ref missing,
                          ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                          ref missing, ref missing);
            newDoc.Close(ref _false, ref missing, ref missing);
            DirectoryInfo dirInfo = new DirectoryInfo(settings.PagesRepository);

            //search for the metadata directory.
            foreach (DirectoryInfo subDir in dirInfo.GetDirectories())
            {
                if (subDir.Name.StartsWith(uniqueName))
                {
                    String suffix = subDir.Name.Replace(uniqueName, "");
                    settings.MetaDataFolderSuffix = suffix;
                    XOfficeCommonSettingsHandler.WriteRepositorySettings(settings);
                }
            }
            if (settings.MetaDataFolderSuffix == "")
            {
                settings.MetaDataFolderSuffix = defaultSuffixValue;
            }
        }
 internal static void SaveDocument(Word.Document document, string saveTo)
 {
     try
     {
         //Подготавливаем параметры для сохранения документа
         Object fileName                = saveTo;
         Object fileFormat              = Word.WdSaveFormat.wdFormatDocumentDefault;
         Object lockComments            = false;
         Object password                = "";
         Object addToRecentFiles_out    = false;
         Object writePassword           = "";
         Object readOnlyRecommended     = false;
         Object embedTrueTypeFonts      = false;
         Object saveNativePictureFormat = false;
         Object saveFormsData           = false;
         Object saveAsAOCELetter        = Type.Missing;
         Object encoding_out            = Type.Missing;
         Object insertLineBreaks        = Type.Missing;
         Object allowSubstitutions      = Type.Missing;
         Object lineEnding              = Type.Missing;
         Object addBiDiMarks            = Type.Missing;
         document.SaveAs(ref fileName,
                         ref fileFormat, ref lockComments,
                         ref password, ref addToRecentFiles_out, ref writePassword,
                         ref readOnlyRecommended, ref embedTrueTypeFonts,
                         ref saveNativePictureFormat, ref saveFormsData,
                         ref saveAsAOCELetter, ref encoding_out, ref insertLineBreaks,
                         ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);
     }
     catch (Exception ex)
     {
         MainClass.OnErrorInLibrary(string.Format("Ошибка сохранения документа: {0}", ex.Message));
     }
 }
Beispiel #24
0
        //将richTextBox带格式的文本另存为word文档
        //先创建一个word文档,全选word文档中的数据,然后全选richTextBox中的数据并复制,粘贴到word文档中,最后保存word文档,并关闭文档
        public void SaveAsWord(string fileName)
        {
            Word.Application app     = new Word.Application();
            Word.Document    doc     = null;
            object           missing = System.Reflection.Missing.Value;
            object           File    = fileName;

            try
            {
                doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                doc.ActiveWindow.Selection.WholeStory();                         //全选
                richTextBoxShow.SelectAll();
                Clipboard.SetData(DataFormats.Rtf, richTextBoxShow.SelectedRtf); //复制RTF数据到剪贴板
                doc.ActiveWindow.Selection.Paste();
                doc.SaveAs(ref File, 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);
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close(ref missing, ref missing, ref missing);
                    doc = null;
                }
                if (app != null)
                {
                    app.Quit(ref missing, ref missing, ref missing);
                    app = null;
                }
            }
        }
Beispiel #25
0
        public bool SaveWordDocument(string path, string filename)
        {
            bool bRet = false;

            try
            {
                path = path.Trim();
                if (path == string.Empty)
                {
                    path = Assembly.GetExecutingAssembly().Location;
                }
                object FileName   = path + "\\" + filename + ".doc";
                object FileFormat = Word.WdSaveFormat.wdFormatDocument;
                m_WordDoc.SaveAs(ref FileName, ref FileFormat, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing, ref missing, ref missing, ref missing,
                                 ref missing);
                ((Word._Document)m_WordDoc).Close(ref missing, ref missing, ref missing);
                ((Word._Application)m_WordApp).Quit(ref missing, ref missing, ref missing);

                bRet = true;
            }
            catch (System.Exception)
            {
                bRet = false;
            }

            return(bRet);
        }
Beispiel #26
0
        private void SaveAs(MSWord.Document mydoc, string filename)
        {
            Object fileName                = filename;
            Object fileFormat              = Type.Missing;
            Object lockComments            = Type.Missing;
            Object password                = Type.Missing;
            Object addToRecentFiles        = Type.Missing;
            Object writePassword           = Type.Missing;
            Object readOnlyRecommended     = Type.Missing;
            Object embedTrueTypeFonts      = Type.Missing;
            Object saveNativePictureFormat = Type.Missing;
            Object saveFormsData           = Type.Missing;
            Object saveAsAOCELetter        = Type.Missing;
            Object encoding                = Type.Missing;
            Object insertLineBreaks        = Type.Missing;
            Object allowSubstitutions      = Type.Missing;
            Object lineEnding              = Type.Missing;
            Object addBiDiMarks            = Type.Missing;
            Object noPrompt                = true;
            Object originalFormat          = Type.Missing;

            mydoc.SaveAs(ref fileName, ref fileFormat, ref lockComments,
                         ref password, ref addToRecentFiles, ref writePassword,
                         ref readOnlyRecommended, ref embedTrueTypeFonts,
                         ref saveNativePictureFormat, ref saveFormsData,
                         ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,
                         ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);
        }
 private void btn_New_Click(object sender, EventArgs e)
 {
     btn_New.Enabled = false;                     //停用新建按钮
     ThreadPool.QueueUserWorkItem(                //使用线程池
         (P_temp) =>                              //使用lambda表达式
     {
         G_wa = new Word.Application();           //创建Word应用程序对象
         Word.Document P_wd = G_wa.Documents.Add( //建立新文档
             ref G_missing, ref G_missing, ref G_missing, ref G_missing);
         Word.Range P_Range = P_wd.Paragraphs[1].Range;
         using (StreamReader P_StreamReader =    //创建流读取器对象
                                              new StreamReader(G_OpenFileDialog.FileName, Encoding.Default))
         {
             P_Range.Text = P_StreamReader.ReadToEnd();
         }
         G_str_path = string.Format(    //计算文件保存路径
             @"{0}\{1}", G_FolderBrowserDialog.SelectedPath,
             DateTime.Now.ToString("yyyy年M月d日h时s分m秒fff毫秒") + ".doc");
         P_wd.SaveAs(    //保存Word文件
             ref G_str_path,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing, ref G_missing,
             ref G_missing, ref G_missing, ref G_missing);
         ((Word._Application)G_wa.Application).Quit( //退出应用程序
             ref G_missing, ref G_missing, ref G_missing);
         this.Invoke(                                //开始执行窗体线程
             (MethodInvoker)(() =>                   //使用lambda表达式
         {
             btn_Display.Enabled = true;             //启用显示按钮
             MessageBox.Show("成功创建Word文档!", "提示!");  //弹出消息对话框
         }));
     });
 }
Beispiel #28
0
 private void PictureBox2_Click(object sender, EventArgs e)
 {
     if (comboBox2.Text == null || comboBox1.Text == null)
     {
         MessageBox.Show("Заполните данныеа");
     }
     else
     {
         try
         {
             Word1.Application app = new Word1.Application();                                     //создание документа
             Word1.Document    doc = app.Documents.Add("C:\\Users\\petya\\Desktop\\Шаблон.docx"); //выбор шаблона
             /*для того что бы поля записались надо добавить закладки в меню вставка>закладка*/
             doc.Bookmarks["sotr"].Range.Text = comboBox2.Text;
             doc.Bookmarks["pos"].Range.Text  = comboBox1.Text;
             doc.Bookmarks["date"].Range.Text = DateTime.Now.ToString("dd.MM.yy");
             doc.SaveAs(FileName: "C:\\Users\\petya\\Desktop\\Краткосрочная карта.doc"); //сохранение документа
             app.Visible = true;                                                         //открытие
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
 }
Beispiel #29
0
        private void NapraviDekodiraniDOCX(String lokacija, String text, String startniFajl)
        {
            Word.Application objWord = new Word.Application();
            objWord.Visible = false;

            Word.Document objDoc = objWord.Documents.Add();

            Word.Paragraph objPara;
            objPara = objDoc.Paragraphs.Add();

            String dekriptovano = Knap.Dekriptuj(text);

            if (!ukljucenFSW || (ukljucenFSW && String.Equals(FSWOdabranFajl, startniFajl)))
            {
                txtIzlaz.Text = dekriptovano;
            }

            objPara.Range.Text = dekriptovano;

            objDoc.SaveAs(lokacija);
            objDoc.Close();
            objWord.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(objWord);
            //if (ukljucenFSW)
            //{
            //    obradjeniFajlovi.Add(lokacija);
            //}
        }
Beispiel #30
0
        private void importoutpdf(object obj)
        {
            object type              = WdBreakType.wdSectionBreakContinuous;
            object missing           = System.Reflection.Missing.Value;
            object confirmConversion = false;
            object link              = false;
            object attachment        = false;

            Word.Document doc = (Word.Document)obj;

            if (doc.FullName.IndexOf(@"\") <= 0)
            {
                MessageBox.Show("File has not saved, please save the file at first!");
                return;
            }

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    Word.Application sword = new Word.Application();
                    Word.Document    sdoc  = sword.Documents.Add();
                    sword.Visible = false;
                    sword.Selection.InsertFile(doc.FullName, ref missing, ref confirmConversion, ref link, ref attachment);
                    sdoc.SaveAs(saveFileDialog1.FileName, Word.WdSaveFormat.wdFormatPDF, 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);
                    sdoc.Close(false, ref missing, ref missing);
                    sword.Quit(false, ref missing, ref missing);
                }
                catch (Exception err)
                {
                    return;
                }
            }
        }
Beispiel #31
0
        public void createWord(string saved_path, bool newSmry)
        {
            word_app = createWordApp();
            this.insertBookmark(saved_doc_list);
            object strFileName = saved_path;
            //MessageBox.Show(strFileName.ToString());
            if (System.IO.File.Exists((string)strFileName))
                System.IO.File.Delete((string)strFileName);
            Object Nothing = System.Reflection.Missing.Value;

            word_wrt = word_app.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            object oStyleName = Word.WdBuiltinStyle.wdStyleBodyText;  //"Heading 1";
            word_wrt.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            word_wrt.Paragraphs.Last.Range.set_Style(ref oStyleName);
            string strContent = "Schlüsselwörter \r";
            word_wrt.Paragraphs.Last.Range.Font.Size = 14;
            word_wrt.Paragraphs.Last.Range.Font.Bold = 1;
            word_wrt.Paragraphs.Last.Range.Text = strContent;

            this.writeSammary();

            //将WordDoc文档对象的内容保存为DOC文档
            word_wrt.SaveAs(ref strFileName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            //关闭WordDoc文档对象
            word_wrt.Close(ref Nothing, ref Nothing, ref Nothing);

            //Test code ##
            this.buildTOC(saved_path, newSmry);
            //Test code ##

            try
            {
                word_show.Quit(ref Nothing, ref Nothing, ref Nothing);
                word_app.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
            catch(Exception)
            {
            }

            word_app = null;
            word_show = null;
        }
Beispiel #32
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     object Nothing = System.Reflection.Missing.Value;//定义一个missing
     wordApp = new Msword.ApplicationClass();//对wordapp进行初始化
     wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);//对一个wordDoc进行初始化
     object filename = "F:\\aa.doc";
     if (File.Exists(filename.ToString()))//判断文件是否存在
     {
         File.Delete(filename.ToString());//若文件存在就删除这个文件
     }
     wordApp.Visible = false;//设置动态建立的word文档可见
     wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档的左边距
     wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));//设置word文档右边距
     wordApp.ActiveWindow.HorizontalPercentScrolled = 11;//设置文档的水平滑动距离
     wordApp.ActiveWindow.View.Type = Msword.WdViewType.wdOutlineView;//设置文档的页眉类型
     wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekCurrentPageHeader;//设置文档的页眉是显示在文档的头部
     wordApp.ActiveWindow.ActivePane.Selection.InsertAfter("这是我的页眉内容");
     wordApp.Selection.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置页眉内容的对齐方式
     //wordApp.ActiveWindow.View.SeekView = Msword.WdSeekView.wdSeekMainDocument;//跳出页眉设置
     wordApp.Selection.ParagraphFormat.LineSpacing = 11f;//设置段落的距离为11f
     Msword.Paragraph para1;//定义一个段落为para1
     para1 = wordDoc.Paragraphs.Add(ref Nothing);//对para1进行初始化
     para1.Range.Text = "这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2这是我的内容2";//对段落para1进行添加内容
     para1.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进
     para1.Range.Font.Color = Msword.WdColor.wdColorBlue;//设置字体的颜色
     para1.Format.SpaceAfter = 6;//在段落para1后面设置空行为6
     para1.Range.InsertParagraphAfter();//将段落para1添加到文档中
     Msword.Paragraph para2;//同上
     object endofdoc = "\\endofdoc";//定义标签endofdoc,"endofdoc"表示文档的末尾书签
     object range1 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//定位到文档的书签处
     para2 = wordDoc.Paragraphs.Add(ref range1);//同上
     para2.Range.Text = "asfdasdfasdfasdffasdfsadfasdfasfdasdfas";//同上
     para2.Range.InsertParagraphAfter();//同上
     Msword.Paragraph para3;//同上
     object range2 = wordDoc.Bookmarks.get_Item(ref endofdoc).Range;//同上
     para3 = wordDoc.Paragraphs.Add(ref range2);//同上
     para3.Range.Text = "eeeeeeeeeeeeeeeeeeeeeeee";//同上
     object sttar = (object)(para3.Range.Start + 2);//"para3.Range.Start "表示para3段落的开始处加上两个字符
     object eend = (object)(para3.Range.Start + 2);//同上
     wordDoc.Range(ref sttar, ref eend).InsertBefore("ttt");//定位到para3段落的开始处加上两个字符并添加内容"ttt"
     para3.Format.CharacterUnitFirstLineIndent = 2;//设置首行缩进
     para3.Range.Font.Bold = 5;//设置段落para3字体颜色
     para3.Range.InsertParagraphAfter();//同上
     Msword.Table table1 = wordDoc.Tables.Add(para3.Range, 8, 8, ref Nothing, ref Nothing);//在文档中添加8行8列的表格
     table1.Cell(1, 1).Range.Font.Color = Msword.WdColor.wdColorBrown;//设置表格中的第1行1列的字体颜色为wdColorBrown
     table1.Cell(1, 1).Range.Text = "搜点的撒旦";//在表格中的第一行第一类中添加内容
     table1.Range.ParagraphFormat.Alignment = Msword.WdParagraphAlignment.wdAlignParagraphRight;//设置表格中的内容alignment
     table1.Cell(3, 3).Merge(table1.Cell(8, 3));//将3行3列一直到8行3列进行组合成一列
     object row = 4;
     object col = 4;
     table1.Cell(3, 1).Split(ref row, ref col);//将3行1列分开为4行4列
     string picturefile = "D:\\ly\\应用\\test.jpg";//设置图片的路径
     object linktofile = false;
     object linktodoctument = true;
     object x1 = (object)(para2.Range.Start);
     object x2 = (object)(para2.Range.End);
     object rr1 = wordDoc.Range(ref x1, ref x2);
     wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(picturefile, ref linktofile, ref linktodoctument, ref rr1);//将图片添加到文档中
     //将图片的外形设置为可变
     Msword.Shape shape1 = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
     shape1.WrapFormat.Type = Msword.WdWrapType.wdWrapSquare;
     //保存wordDoc
     wordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
         ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
         ref Nothing, ref Nothing);
     //释放内存
     wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
     wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
 }
Beispiel #33
0
        public override void SaveFileAs(string fileName, FileType type)
        {
            object Visible = false;
            object start1 = 0;
            object end1 = 0;

            WordApp = new Word.Application();
            doc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            Range rng = doc.Range(ref start1, ref missing);
            rng.InsertAfter(parsedFile.contentRaw);
            object filename = fileName;

            doc.SaveAs(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);

            WordApp.Visible = true;
            //doc.RemoveDocumentInformation(WdRemoveDocInfoType.wdRDIAll);
            //doc.DocumentInspectors;
        }
Beispiel #34
0
        void RunSummary()
        {
            NotamFilter filter = new NotamFilter();
            
            filter.TypeFilter = NType;
            filter.FromDateFilter = FromDate;
            filter.ToDateFilter = ToDate;
            _notamService.Archive();
            List<Notam> notamList = _notamService.GetFilterNotams(filter);
            List<string> aeroList = notamList.Select(x => x.FirAero).ToList<string>();
            Dictionary<string, string> aeroDic = _aerodomService.GetAddressList(aeroList);
            object fileName = System.Configuration.ConfigurationManager.AppSettings.Get("DocTemplatePath").ToString();
            Word.Application word = new Word.Application();
            Word.Document doc = new Word.Document();
            object missing = System.Type.Missing;
            try
            {
                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);
                doc.Activate();
                string newFileName = fileName.ToString();
                newFileName = newFileName.Replace(".docx", "1.docx");
                doc.SaveAs(newFileName);
                Process.Start(newFileName.ToString());
                int icol = 2, irow = 1;
                var queryYear = notamList.GroupBy(item => item.Year).Select(group =>
                                        new
                                        {
                                            Year = group.Key,
                                            nums = group.OrderBy(x => x.Number)
                                        }).OrderBy(group => group.nums.First().Number);
                Word.Table newTable = doc.Application.ActiveDocument.Tables[1];
                //                newTable.Rows.Add(newTable.Rows[1]);
                foreach (var yearItem in queryYear)
                {
                    newTable.Cell(irow, 1).Range.Text = "20" + yearItem.Year + ":";
                    foreach (var nt in yearItem.nums)
                    {
                        if (icol > 14)
                        {
                            icol = 2;
                            irow++;
                            newTable.Rows.Add(ref missing);

                        }
                        if (nt.Number!=null)
                            newTable.Cell(irow, icol).Range.Text = nt.Number.ToString();
                        doc.Save();
                        icol++;
                    }
                    irow++;
                    icol = 2;
                    newTable.Rows.Add(ref missing);
                    doc.Save();
                }
                

                //add0519
                var queryAero = notamList.Where(x => x.FirAero!=null).GroupBy(item => item.FirAero).Select(group =>
                        new
                        {
                            Aero = group.Key,
                            Addr = aeroDic.ContainsKey(group.Key) ? aeroDic[group.Key]:"",
                            nums = group.OrderBy(x => x.Number)
                        }).OrderBy(group => group.Addr);
                Word.Table secTable = doc.Application.ActiveDocument.Tables[2];
                irow = 1;
                //                newTable.Rows.Add(newTable.Rows[1]);
                
                foreach (var aeroItem in queryAero)
                {
                    secTable.Rows.Add(ref missing);
                    irow++;
                    secTable.Cell(irow, 3).Range.Font.Size = 11;
                    secTable.Cell(irow, 3).Range.Font.Bold = 1;
                    secTable.Cell(irow, 3).Range.Font.Italic = 1;
                    string strAeroCity = aeroItem.Addr;
                    secTable.Cell(irow, 3).Range.Text = strAeroCity + "." + aeroItem.Aero;
                    doc.Save();

                    foreach (var nt in aeroItem.nums)
                    {
                        secTable.Rows.Add(ref missing);
                        irow++;
                        secTable.Cell(irow, 1).Range.Font.Bold = 0;
                        secTable.Cell(irow, 1).Range.Font.Italic = 0;
                        secTable.Cell(irow, 1).Range.Font.Size = 10;
                        if (nt.Number!=null)
                            secTable.Cell(irow, 1).Range.Text = nt.Type+ nt.Number.ToString();
                        secTable.Cell(irow, 2).Range.Font.Bold = 0;
                        secTable.Cell(irow, 2).Range.Font.Italic = 0;
                        secTable.Cell(irow, 2).Range.Font.Size = 10;
                        if (nt.FromDate!=null)
                            secTable.Cell(irow, 2).Range.Text = nt.FromDate.Substring(0, 6);
                        string str = nt.FromDate + "/" + nt.ToDate + "/" + nt.PermEst + "\n";
                        string iteme = nt.EFreeText;
                        secTable.Cell(irow, 3).Range.Font.Bold = 0;
                        secTable.Cell(irow, 3).Range.Font.Italic = 0;
                        secTable.Cell(irow, 3).Range.Font.Size = 9;
                        secTable.Cell(irow, 3).Range.Text = str + iteme;
                        doc.Save();

                    }
                }


                doc.Save();
                MessageBox.Show("Summary created successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }

        }
Beispiel #35
0
        ///<summary>
        ///Procedimiento al que llamaremos para inciar el proceso de marcación
        ///</summary>
        public void startMarkup()
        {
            if (log.IsInfoEnabled) log.Info("Begin");
            /* Declaracion de variables */
            Boolean marked = false;
            Boolean parsed = false;
            String originalString = null;
            String fixedMarkedString = null;
            String issn = null;
            String pathXML = null;
            String clearTag = null;
            Word.Selection docSeleccion = null;
            this.xmlDoc = new XmlDocument();
            List<MarkupStruct> citas = null;
            RegexOptions options = RegexOptions.None;
            Regex objRegExp = new Regex(@"\[[^\]]+?\]", options);;
            Dictionary<String, String> altRule = new Dictionary<String, String>(){
                {"doc", "0000-0000"},
                {"article", "XXXX-XXXX"},
                {"text", "XXXX-XXXX"}
            };
            /*Definiendo directorios de los xml*/
            if (ApplicationDeployment.IsNetworkDeployed)
            {
                pathXML = Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "regex.xml");
            }
            else {
                pathXML = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "regex.xml");
            }
            /*Verificamos si vamos a usar un archivo externo para las reglas*/
            if (Settings.Default.useExternalRegexFile) {
                pathXML = Settings.Default.externalRegexFile;
            }
            /* Inicializamos variables */
            ActiveDocument = Globals.ThisAddIn.Application.ActiveDocument;
            /* Leemos y verificamos que el issn exista */
            this.dtdType = "article";
            issn = utils.getAttrValueInTag("article", "issn");
            /* Verificamos la existencia de text */
            if (issn == null) {
                issn = utils.getAttrValueInTag("text", "issn");
                this.dtdType = "text";
            }

            /* Verificamos la existencia de doc */
            if (issn == null)
            {
                issn = utils.getAttrValueInTag("doc", "issn");
                this.dtdType = "doc";
            }

            if (log.IsDebugEnabled) log.Debug("issn: " + issn);
            if (issn == null) {
                MessageBox.Show(Resources.RegexMarkup_issnNotDefined, Resources.RegexMarkup_title);
            } else {
                /*Asignamos el numero de version de la DTD*/
                this.dtdVersion = utils.getAttrValueInTag(this.dtdType, "version");
                this.dtdVersion = this.dtdVersion == null ? "4.0" : this.dtdVersion;
                /* Cargamos el archivo xml donde se encuetran los patrones de las revistas */
                try
                {
                    this.xmlDoc.Load(pathXML);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    return;
                }
                /* Leemos el nodo correspondiente al issn de la revista */
                this.serialNode = this.xmlDoc.SelectSingleNode("//*[@issn=\"" + issn + "\"]");
                /* Si no existe una regla para la revista cargamos una generica */
                this.serialNode = this.serialNode == null ? this.xmlDoc.SelectSingleNode("//*[@issn=\"" + altRule[this.dtdType] + "\"]") : this.serialNode;
                /* Asignamos el estilo de la citación */
                this.citationStyle = this.serialNode.SelectSingleNode("norm").InnerText.Trim();
                if (this.dtdType == "doc")
                    this.citationStyle = "refs";
                /* Verificamos que la seleccion sea del parrafo completo */
                Word.Range start = Globals.ThisAddIn.Application.Selection.Range;
                docSeleccion = Globals.ThisAddIn.Application.Selection;
                if (docSeleccion.Start != docSeleccion.Paragraphs.First.Range.Start || docSeleccion.End != docSeleccion.Paragraphs.Last.Range.End){
                    MessageBox.Show(Resources.RegexMarkup_selectCitationComplete, Resources.RegexMarkup_title);
                } else {
                    /* Asignamos el texto de la seleccion a subjectString */
                    if (log.IsInfoEnabled) log.Info("Select paragraphs");
                    /* Inicializando arratlist de citas */
                    citas = new List<MarkupStruct>();
                    /*Creamos una instancia del formulario*/
                    this.formValidate = ValidateMarkup.Instance;
                    this.formValidate.CitationStyle = this.citationStyle;
                    this.formValidate.DtdVersion = this.dtdVersion;
                    this.formValidate.DtdType = this.dtdType;
                    this.formValidate.updateDTDInfo();
                    /* Buscando parrafo por parrafo */
                    foreach (Word.Paragraph parrafo in docSeleccion.Paragraphs){
                        fixedMarkedString = null;
                        marked = false;
                        parsed = false;
                        /* Mandamos el texto de cada parrafo a una funcion que nos lo regresara marcado y quitamos el salto linea */
                        object parrafoStart = parrafo.Range.Start;
                        object parrafoEnd = (parrafo.Range.End - 1);
                        originalString = ActiveDocument.Range(ref parrafoStart, ref parrafoEnd).Text;
                        //MessageBox.Show(subjetcString, "Texto de parrafo");
                        if (originalString != null)
                        {
                            /*Verificamos si la cadena original ya esta marcada*/
                            if (originalString.IndexOf("[") == 0 && originalString.LastIndexOf("]") == originalString.Length - 1)
                            {
                                marked = true;
                                parsed = true;
                                fixedMarkedString = originalString;
                                clearTag = fixedMarkedString.Substring(1, fixedMarkedString.IndexOf("]") - 1);
                                /*Nos aseguramos de que la etiqueta no contenga algun atributo buscando un espacio*/
                                if(clearTag.IndexOf(" ") > 0){
                                    clearTag = clearTag.Substring(0, clearTag.IndexOf(" "));
                                }
                                /*Con la ayuda de la instancia del formulario limpiamos la cadena marcada*/
                                this.tags.getChilds(clearTag);
                                originalString = this.formValidate.clearTag(fixedMarkedString, clearTag);
                            }
                            citas.Add(new MarkupStruct(originalString, fixedMarkedString, ActiveDocument.Range(ref parrafoStart, ref parrafoEnd), marked, parsed));
                        }
                    }
                    /* Mandamos llamar al formulario para la validación de las citas*/
                    this.formValidate.startValidate(ref citas);

                    if (this.formValidate.ShowDialog() == DialogResult.OK)
                    {
                        /* Ocultamos la aplicacion durante los procesos de reemplazo y coloreado para hacer mas rapida la aplicacion */
                        Globals.ThisAddIn.Application.Visible = false;
                        waitForm = Waiting.Instance;
                        waitForm.Show();
                        /* Reemplzando texto original por el marcado */
                        /* Utilizando el rango de texto de la cita original y reemplzado el texto por el marcado */
                        int citaIndex = 0;
                        foreach (MarkupStruct cita in citas)
                        {
                            if (cita.Marked && cita.Colorized)
                            {
                                Clipboard.Clear();
                                cita.MarkedRtb.SelectAll();
                                Clipboard.SetText(cita.MarkedRtb.SelectedRtf, TextDataFormat.Rtf);
                                cita.RngCita.Paste();
                                cita.RngCita.Font.Size = 11;
                                Clipboard.Clear();
                            }
                            if (this.dtdType == "doc") {
                                if (citaIndex == 0)
                                    cita.RngCita.InsertBefore("[refs]");
                                if (citaIndex == (citas.Count - 1))
                                    cita.RngCita.InsertAfter("[/refs]");
                            }
                            citaIndex++;
                        }
                        /* Mostramos de nuevo la aplicacion */
                        waitForm.Hide();
                        Globals.ThisAddIn.Application.Visible = true;
                        /*Guardamos los cambios*/
                        if (!ActiveDocument.ReadOnly)
                        {
                            object FileName = Path.Combine(ActiveDocument.Path, ActiveDocument.Name);
                            object FileFormat = Word.WdSaveFormat.wdFormatFilteredHTML;
                            if (!ActiveDocument.Path.Contains(".htm"))
                                FileFormat = missing;
                            try
                            {
                                ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing,
                                        ref missing, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing);
                            }catch (Exception e)
                            {
                                if (log.IsErrorEnabled) log.Error(e.Message);
                            }
                        }
                        else
                        {
                            MessageBox.Show(Resources.RegexMarkup_messageOnlyRead);
                        }
                    }
                }
            }
            if (log.IsInfoEnabled) log.Info("End");
        }