예제 #1
0
        public void ResetOnDocumentActivate(_Document activeDoc)
        {
            try
            {
                if (activeDoc.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject)
                {
                    PersistenceManager.ActiveAssemblyDoc = (AssemblyDocument)activeDoc;
                    ReferenceManager.KeyManager          = PersistenceManager.ActiveAssemblyDoc.ReferenceKeyManager;
                }

                else if (activeDoc.DocumentType == DocumentTypeEnum.kDrawingDocumentObject)
                {
                    PersistenceManager.ActiveDrawingDoc = (DrawingDocument)activeDoc;
                    ReferenceManager.KeyManager         = PersistenceManager.ActiveDrawingDoc.ReferenceKeyManager;
                }

                else if (activeDoc.DocumentType == DocumentTypeEnum.kPartDocumentObject)
                {
                    PersistenceManager.ActivePartDoc = (PartDocument)activeDoc;
                    ReferenceManager.KeyManager      = PersistenceManager.ActivePartDoc.ReferenceKeyManager;
                }

                else
                {
                    ResetOnDocumentDeactivate();
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
예제 #2
0
파일: Edit.cs 프로젝트: Maxim2045/XXX
        public void EditClick(RichTextBox docBox)
        {
            docBox.Document.Blocks.Clear();
            OpenFileDialog ofd = new OpenFileDialog //Выбор файла для редактирования
            {
                Filter           = "Word files (*.docx)|*.docx|All files (*.*)|*.*",
                InitialDirectory = Path.Combine(
                    Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]))
            };

            if (ofd.ShowDialog() == true)
            {
                Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();
                object File       = ofd.FileName;
                object nullobject = System.Reflection.Missing.Value;
                wordObject.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                _Document docs = wordObject.Documents.Open(ref File, ref nullobject, ref nullobject, ref nullobject, ref nullobject,
                                                           ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject,
                                                           ref nullobject, ref nullobject, ref nullobject, ref nullobject, ref nullobject);
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                docBox.Paste();
                docs.Close(ref nullobject, ref nullobject, ref nullobject);
                wordObject.Quit();
            }
            else
            {
                MessageBox.Show("Отмена редактирования");
            }
        }
예제 #3
0
        internal WordDocument(_Document document)
        {
            if (document == null)
                throw new ArgumentNullException("document");

            _document = document;
        }
    public static void Main()
    {
        var file = new FileInfo("input.html");

        Microsoft.Office.Interop.Word.Application app
            = new Microsoft.Office.Interop.Word.Application();
        try
        {
            app.Visible = true;
            object    missing = Missing.Value;
            object    visible = true;
            _Document doc     = app.Documents.Add(ref missing,
                                                  ref missing,
                                                  ref missing,
                                                  ref visible);
            var bookMark = doc.Words.First.Bookmarks.Add("entry");
            bookMark.Range.InsertFile(file.FullName);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            app.Quit();
        }
    }
예제 #5
0
파일: DocToPdf.cs 프로젝트: Brinews/Code
        public bool ConvertToPdf(String docFolder, String docFile, 
            String pdfFolder, String pdfFile)
        {
            WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF;
            bool result;
            object paramMissing = Type.Missing;

            try
            {
                object paramSourceDocPath = docFolder + "/" + docFile;
                string paramExportFilePath = pdfFolder + "/" + pdfFile;

                WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                WdExportCreateBookmarks paramCreateBookmarks =
                        WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                _wordDoc = _wordApp.Documents.Open(
                        ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing);

                if (_wordDoc != null)
                    _wordDoc.ExportAsFixedFormat(paramExportFilePath,
                            paramExportFormat, paramOpenAfterExport,
                            paramExportOptimizeFor, paramExportRange, paramStartPage,
                            paramEndPage, paramExportItem, paramIncludeDocProps,
                            paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                            paramBitmapMissingFonts, paramUseISO19005_1,
                            ref paramMissing);
                result = true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                _wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                _wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing);

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
예제 #6
0
 private void StartupWord()
 {
     oWord         = new Application();
     oWord.Visible = false;
     oDoc          = oWord.Documents.Add(ref missing, ref missing,
                                         ref missing, ref missing);
 }
예제 #7
0
        //保存文件
        public static bool SaveFile(string filePath, MyNode myNode)
        {
            try
            {
                //初始化
                object fileobj = filePath;
                object unknow  = System.Reflection.Missing.Value;
                //打开word程序,创建一个新的word文档,但是还没有保存到硬盘中
                ApplicationClass wordApp = new ApplicationClass();
                _Document        doc     = wordApp.Documents.Add(ref unknow, ref unknow, ref unknow, ref unknow);

                //这里开始写文件
                //深度优先遍历
                //saveNode(doc, myNode,1);


                //保存word文档
                doc.SaveAs(ref fileobj, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
                doc.Close(ref unknow, ref unknow, ref unknow);
                wordApp.Documents.Save(ref unknow, ref unknow);
                wordApp.Quit(ref unknow, ref unknow, ref unknow);
                return(true);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
예제 #8
0
        /// <summary>
        /// 动态生成Word文档并填充内容
        /// </summary>
        /// <param name="dir">文档目录</param>
        /// <param name="fileName">文档名</param>
        /// <returns>返回自定义信息</returns>
        public static bool CreateWordFile(string dir, string fileName)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;

                if (!Directory.Exists(dir))
                {
                    //创建文件所在目录
                    Directory.CreateDirectory(dir);
                }

                //创建Word文档(Microsoft.Office.Interop.Word)
                _Application WordApp = new Application();
                //WordApp.Visible = true;
                _Document WordDoc = WordApp.Documents.Add(
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                //保存
                object filename = dir + fileName;
                WordDoc.SaveAs(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);
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
예제 #9
0
 public void OpenDocument(string fullFileName)
 {
     wordApp = new ApplicationClass();
     wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
     wordApp.Visible       = false;
     wordDoc = wordApp.Documents.Open(fullFileName);
 }
예제 #10
0
        private void CreateWordDocument()
        {
            _Document oDoc = null;

            try
            {
                Word._Application oWord  = new Word.Application();
                string            source = @"C:\Users\temch\Desktop\Шаблон.dotx";
                oDoc = oWord.Documents.Add(source);
                Word.Bookmarks wBookmarks = oDoc.Bookmarks;
                Word.Range     wRange;
                string[]       arr = { "27", "Tema", "Shevchenko" };
                int            i   = 0;
                foreach (Word.Bookmark mark in wBookmarks)
                {
                    wRange      = mark.Range;
                    wRange.Text = arr[i];
                    i++;
                }
                string pathToSaveObj = @"C:\Users\temch\Desktop\Контракт.docx";
                oDoc.SaveAs2(pathToSaveObj);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                oDoc.Close();
                oDoc = null;
            }
        }
예제 #11
0
        private void makePlanBTN_Click(object sender, EventArgs e)
        {
            var dialogResult = MessageBox.Show(@"Вы действительно хотите составить план за " + monthTB.Text.ToLower() + @" " + yearTB.Text + @" года?",
                                               @"Создание плана", MessageBoxButtons.YesNo);

            if (dialogResult != DialogResult.Yes)
            {
                return;
            }
            _Application application = new Application();
            _Document    document    = application.Documents.Add();
            Paragraph    paragraph   = document.Content.Paragraphs.Add();

            application.Visible = true;

            paragraph.Range.Font.Bold = 0;
            paragraph.Range.Font.Size = 14;
            paragraph.Range.Font.Name = "Times New Roman";
            paragraph.Alignment       = WdParagraphAlignment.wdAlignParagraphLeft;
            paragraph.Range.Text      = $"Дата: {monthTB.Text.ToLower()} {yearTB.Text} год\n" +
                                        $"Количество заказов: {numOrdersTB.Text}\n" +
                                        $"Доход: {incomeTB.Text} руб.\n" +
                                        $"Расход: {consumptionTB.Text} руб.\n" +
                                        $"Чистый заработок: {Convert.ToInt32(incomeTB.Text) - Convert.ToInt32(consumptionTB.Text)} руб.";
            document.SaveAs(Environment.CurrentDirectory + "\\Планы\\" + monthTB.Text.ToLower() + "_" + yearTB.Text, WdSaveFormat.wdFormatDocumentDefault);
        }
예제 #12
0
 private void SaveAs(string SaveAsPath)
 {
     System.IO.FileInfo fileInfo = new System.IO.FileInfo(SaveAsPath);
     if (fileInfo.Extension.ToLower().Equals(".pdf"))
     {
         base.ConvertToPdf(SaveAsPath);
     }
     else
     {
         object    obj      = SaveAsPath;
         _Document arg_C9_0 = this.WordApp.ActiveDocument;
         object    value    = System.Reflection.Missing.Value;
         object    value2   = System.Reflection.Missing.Value;
         object    value3   = System.Reflection.Missing.Value;
         object    value4   = System.Reflection.Missing.Value;
         object    value5   = System.Reflection.Missing.Value;
         object    value6   = System.Reflection.Missing.Value;
         object    value7   = System.Reflection.Missing.Value;
         object    value8   = System.Reflection.Missing.Value;
         object    value9   = System.Reflection.Missing.Value;
         object    value10  = System.Reflection.Missing.Value;
         object    value11  = System.Reflection.Missing.Value;
         object    value12  = System.Reflection.Missing.Value;
         object    value13  = System.Reflection.Missing.Value;
         object    value14  = System.Reflection.Missing.Value;
         object    value15  = System.Reflection.Missing.Value;
         arg_C9_0.SaveAs(ref obj, ref value, ref value2, ref value3, ref value4, ref value5, ref value6, ref value7, ref value8, ref value9, ref value10, ref value11, ref value12, ref value13, ref value14, ref value15);
     }
 }
예제 #13
0
        ///<summary>
        ///</summary>
        ///<param name="document"></param>
        ///<returns></returns>
        public static ControlProperties[] Load(_Document document)
        {
            Log.Debug(string.Format(CultureInfo.InvariantCulture, "ControlsStorage - Load : document {0}", document));

            ControlProperties[] controls = null;
            CustomXMLParts      parts    = document.CustomXMLParts.SelectByNamespace(ControlsStorageNamespace);

            if (parts != null && parts.Count > 0)
            {
                Debug.Assert(parts.Count == 1);
                CustomXMLPart part = parts[1];
                XmlDocument   doc  = new XmlDocument();
                doc.LoadXml(part.XML);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("sc", ControlsStorageNamespace);

                XmlElement controlsElement =
                    doc.SelectSingleNode(String.Format(CultureInfo.CurrentUICulture, "//sc:{0}", ControlsNodeName),
                                         nsmgr) as XmlElement;
                if (controlsElement != null)
                {
                    byte[]          data      = Convert.FromBase64String(controlsElement.InnerXml);
                    BinaryFormatter formatter = new BinaryFormatter();
                    controls = (ControlProperties[])formatter.Deserialize(new MemoryStream(data));
                }
            }

            return(controls);
        }
예제 #14
0
        private Table CreateTable(_Document aDoc, int noOfRows, int noOfColumns, Range rng, int tblCount)
        {
            if (aDoc == null)
            {
                throw new ArgumentNullException("aDoc");
            }

            //object start = Type.Missing;
            //object end = Type.Missing;
            //object count = Type.Missing;
            //object unit = Type.Missing;

            //aDoc.Range(ref start, ref end).Delete(ref unit, ref count);


            //Range rng = aDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            rng.SetRange(rng.End, rng.End);

            object defaultTableBehaviour = Type.Missing;
            object autoFitBehaviour      = Type.Missing;

            aDoc.Tables.Add(rng, noOfRows, noOfColumns, ref defaultTableBehaviour, ref autoFitBehaviour);
            Table tbl = aDoc.Tables[tblCount];

            return(tbl);
        }
예제 #15
0
        public static void RemoveCitations(string f_name)
        {
            _Application word_app = new Application();

            word_app.Visible = false;

            object    missing             = Type.Missing;
            object    filename            = f_name;
            object    confirm_conversions = false;
            object    read_only           = false;
            object    add_to_recent_files = false;
            object    format   = 0;
            _Document word_doc =
                word_app.Documents.Open(ref filename,
                                        ref confirm_conversions,
                                        ref read_only, ref add_to_recent_files,
                                        ref missing, ref missing, ref missing, ref missing,
                                        ref missing, ref format, ref missing, ref missing,
                                        ref missing, ref missing, ref missing, ref missing);

            object index = 1;

            while (word_doc.Hyperlinks.Count > 0)
            {
                word_doc.Hyperlinks.get_Item(ref index).Delete();
            }

            object save_changes = true;

            word_doc.Close(ref save_changes, ref missing, ref missing);

            word_app.Quit(ref save_changes, ref missing, ref missing);
            Console.WriteLine("Done");
        }
예제 #16
0
        ///<summary>
        ///</summary>
        ///<param name="document"></param>
        ///<param name="controls"></param>
        public static void Store(_Document document, ControlProperties[] controls)
        {
            Log.Debug(string.Format(CultureInfo.InvariantCulture, "ControlsStorage - Store : controls count {0}", controls.Length));
            string xml = null;

            using (MemoryStream memStream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(memStream, controls);

                XmlDocument doc  = new XmlDocument();
                XmlElement  root = doc.CreateElement(RootNodeName, ControlsStorageNamespace);
                doc.AppendChild(root);

                XmlElement controlsDataNode = doc.CreateElement(ControlsNodeName, ControlsStorageNamespace);
                controlsDataNode.InnerXml = Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length);
                root.AppendChild(controlsDataNode);

                xml = doc.InnerXml;
            }

            CustomXMLParts parts = document.CustomXMLParts.SelectByNamespace(ControlsStorageNamespace);

            if (parts.Count > 0)
            {
                Debug.Assert(parts.Count == 1);
                parts[1].Delete();
            }

            document.CustomXMLParts.Add(xml, Type.Missing);
        }
예제 #17
0
        public bool save(string str)
        {
            if (this.word == null)
            {
                return(false);
            }

            //Save the file, use default values except for filename.  The
            //DocumentBeforeSave event will fire.
            object fileName = str; //+= "_new";

            try
            {
                _Document doc      = word.ActiveDocument;
                object    optional = Missing.Value;

                doc.SaveAs(ref fileName,
                           ref optional, ref optional, ref optional,
                           ref optional, ref optional, ref optional,
                           ref optional, ref optional, ref optional,
                           ref optional, ref optional, ref optional,
                           ref optional, ref optional, ref optional);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #18
0
        private _Document GetDoc(string path)
        {
            _Document oDoc = oWord.Documents.Add(path);

            SetTemplate(oDoc);
            return(oDoc);
        }
예제 #19
0
        public void CreateDocument(string docFilePath, Image image)
        {
            _Application oWord = new Microsoft.Office.Interop.Word.Application();
            //Nếu tạo một Document
            _Document oDoc = oWord.Documents.Add();

            //Nếu mở một Document
            //Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Open(docFilePath, ReadOnly: false, Visible: true);

            //Để xem điều gì đang xảy ra trong khi điền tập tài liệu từ Visible = true
            oWord.Visible = true;

            //Chèn ảnh từ mảng byte vào MS Word, sử dụng Clipboard để dán Image vào tài liệu
            Object oMissing = System.Reflection.Missing.Value;

            Clipboard.SetDataObject(image);
            var oPara = oDoc.Content.Paragraphs.Add(ref oMissing);

            oPara.Range.Paste();
            oPara.Range.InsertParagraphAfter();

            //Nếu tạo document
            oDoc.SaveAs(docFilePath);
            //Nếu mở một document
            //oDoc.Save();
            oDoc.Close();
            oWord.Quit();
        }
        /// <summary>
        /// Печать акта приёмки заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrint_Click(object sender, EventArgs e)
        {
            var templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "акт выдачи оборудования.dotx");

            if (!File.Exists(templateFile))
            {
                throw new Exception("Не найден файл " + templateFile);
            }
            var       oWord           = new Word.Application();
            _Document oDoc            = null;
            var       newTemplateFile = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                $"Акты выдачи\\акт_выдачи_оборудования_{DateTime.Now:dd.MM.yyyy_HH.mm.ss}_{this.textBoxFIO.Text}.docx");

            try
            {
                oDoc = oWord.Documents.Add(templateFile);
                this.SetTemplate(oDoc);

                oDoc.SaveAs2(FileName: newTemplateFile);
            }
            finally
            {
                oDoc?.Close();
                oWord.Quit();
            }
            MessageBox.Show("Сохранение прошло успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Process.Start(newTemplateFile);
        }
예제 #21
0
        public void Print()
        {
            _Application wordApplication = null;
            Documents    docs            = null;
            _Document    doc             = null;

            try
            {
                wordApplication = new Application();
                docs            = wordApplication.Documents;
                doc             = docs.Add(_path);

                WriteFields(doc.Fields);
                //Insert table for schedule details
                var wrdRng       = doc.Bookmarks["TableLocation"].Range;
                var detailsTable = doc.Tables.Add(wrdRng, _report.Details.Count + 1, _report.PropertiesCount);
                detailsTable.Range.ParagraphFormat.SpaceAfter = 6;

                var headerRow = detailsTable.Rows[1];
                WriteHeaderRow(headerRow);
                StyleHeaderRow(headerRow);
                var tableRows = detailsTable.Rows;
                WriteDetails(tableRows, _report.Details);
                ApplyTableStyle(detailsTable);
                wordApplication.Visible = true;
            }
            catch
            {
                ReleaseResources(wordApplication, docs, doc);
                throw;
            }
        }
예제 #22
0
 public Form1(string file_name, string path)
 {
     this.oWord = new Word.Application();
     this.oDoc  = oWord.Documents.Add(path);
     this.name  = file_name;
     InitializeComponent();
 }
예제 #23
0
        public void MilReportEmployeesCreator(List <MilReportEmployees> list)
        {
            string emplData = "";

            foreach (MilReportEmployees empl in list)
            {
                emplData += empl.idx.ToString() + ";" + empl.personInfo + ";" + empl.birthDate + ";" +
                            empl.milRank + ";" + empl.emplAddress + ";" + empl.position + "\n";
            }

            object m            = System.Reflection.Missing.Value;
            object templateFile = currDir + "\\milEmplTemplate.docx";
            object readOnly     = (object)false;

            _Application word = new Application();

            word.Visible = true;
            _Document document = word.Documents.Add(ref templateFile, ref m, ref m, ref m);

            Table templateTable = document.Tables[1];
            Range rngTbl        = templateTable.Range;

            rngTbl.Collapse(WdCollapseDirection.wdCollapseEnd);
            Range rng = document.Content;

            rng.Collapse(WdCollapseDirection.wdCollapseEnd);
            rng.Text      = emplData;
            rng.Font.Size = 12;
            Table tblExtend = rng.ConvertToTable(";", m, m, m, m,
                                                 m, m, m, m, m, m, m, m, m,
                                                 m, WdDefaultTableBehavior.wdWord8TableBehavior);

            tblExtend.Range.Cut();
            rngTbl.PasteAppendTable();
        }
예제 #24
0
        // Замена закладки  на данные введенные в textBox
        private void SetTemplate(_Document oDoc)
        {
            oDoc.Bookmarks["F"].Range.Text = maskedTextBox1.Text;
            oDoc.Bookmarks["I"].Range.Text = maskedTextBox3.Text;
            oDoc.Bookmarks["O"].Range.Text = maskedTextBox4.Text;

            oDoc.Bookmarks["Kyrc"].Range.Text   = maskedTextBox6.Text;
            oDoc.Bookmarks["Gryppa"].Range.Text = maskedTextBox5.Text;
            oDoc.Bookmarks["Dada_p"].Range.Text = maskedTextBox7.Text;
            oDoc.Bookmarks["Tema"].Range.Text   = maskedTextBox2.Text;

            oDoc.Bookmarks["Data_s"].Range.Text = label1.Text;
            oDoc.Bookmarks["oz_1"].Range.Text   = label10.Text;
            oDoc.Bookmarks["oz_2"].Range.Text   = label27.Text;

            oDoc.Bookmarks["q1"].Range.Text   = Mark_Radio(radioButton1, radioButton2, radioButton3, radioButton4, radioButton5, radioButton6, radioButton7, radioButton8, radioButton9, radioButton10, radioButton11).ToString();
            oDoc.Bookmarks["q2"].Range.Text   = Mark_Radio(radioButton12, radioButton13, radioButton14, radioButton15, radioButton16, radioButton17, radioButton18, radioButton19, radioButton20, radioButton21, radioButton22).ToString();
            oDoc.Bookmarks["q3"].Range.Text   = Mark_Radio(radioButton23, radioButton24, radioButton25, radioButton26, radioButton27, radioButton28, radioButton29, radioButton30, radioButton31, radioButton32, radioButton33).ToString();
            oDoc.Bookmarks["q4"].Range.Text   = Mark_Radio(radioButton34, radioButton35, radioButton36, radioButton37, radioButton38, radioButton39, radioButton40, radioButton41, radioButton42, radioButton43, radioButton44).ToString();
            oDoc.Bookmarks["q5"].Range.Text   = Mark_Radio(radioButton45, radioButton46, radioButton47, radioButton48, radioButton49, radioButton50, radioButton51, radioButton52, radioButton53, radioButton54, radioButton55).ToString();
            oDoc.Bookmarks["q6"].Range.Text   = Mark_Radio(radioButton56, radioButton57, radioButton58, radioButton59, radioButton60, radioButton61, radioButton62, radioButton63, radioButton64, radioButton65, radioButton66).ToString();
            oDoc.Bookmarks["q7"].Range.Text   = Mark_Radio(radioButton67, radioButton68, radioButton69, radioButton70, radioButton71, radioButton72, radioButton73, radioButton74, radioButton75, radioButton76, radioButton77).ToString();
            oDoc.Bookmarks["q8"].Range.Text   = Mark_Radio(radioButton78, radioButton79, radioButton80, radioButton81, radioButton82, radioButton83, radioButton84, radioButton85, radioButton86, radioButton87, radioButton88).ToString();
            oDoc.Bookmarks["q9"].Range.Text   = Mark_Radio(radioButton89, radioButton90, radioButton91, radioButton92, radioButton93, radioButton94, radioButton95, radioButton96, radioButton97, radioButton98, radioButton99).ToString();
            oDoc.Bookmarks["q10"].Range.Text  = Mark_Radio(radioButton100, radioButton101, radioButton102, radioButton103, radioButton104, radioButton105, radioButton106, radioButton107, radioButton108, radioButton109, radioButton110).ToString();
            oDoc.Bookmarks["q11"].Range.Text  = Mark_Radio(radioButton111, radioButton112, radioButton113, radioButton114, radioButton115, radioButton116, radioButton117, radioButton118, radioButton119, radioButton120, radioButton121).ToString();
            oDoc.Bookmarks["q12"].Range.Text  = Mark_Radio(radioButton122, radioButton123, radioButton124, radioButton125, radioButton126, radioButton127, radioButton128, radioButton129, radioButton130, radioButton131, radioButton132).ToString();
            oDoc.Bookmarks["text"].Range.Text = textBox1.Text;
            // если нужно заменять другие закладки, тогда копируем верхнюю строку изменяя на нужные параметры
        }
예제 #25
0
파일: wordHelp.cs 프로젝트: zxbe/EFX.Core
        public static bool WordToHtml(string wordFileName, string htmlFileName)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application WordApp = new Microsoft.Office.Interop.Word.Application();
                WordApp.Visible = false;
                object    filename = wordFileName;
                _Document WordDoc  = WordApp.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);

                // Type wordType = WordApp.GetType();
                // 打开文件
                Type docsType = WordApp.Documents.GetType();
                // 转换格式,另存为
                Type   docType      = WordDoc.GetType();
                object saveFileName = htmlFileName;
                docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc,
                                     new object[] { saveFileName, WdSaveFormat.wdFormatHTML });

                //保存
                WordDoc.Save();
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
예제 #26
0
 private CustomTaskPane FindTaskPane(_Document document, UserControl content)
 {
     if (document == null)
     {
         return(null);
     }
     return(CustomTaskPanes.FirstOrDefault(pane => (pane.Control == content) && (pane.Window == document.ActiveWindow)));
 }
 void _applicationEvents_OnCloseDocument(_Document DocumentObject, string FullDocumentName, EventTimingEnum BeforeOrAfter, NameValueMap Context, out HandlingCodeEnum HandlingCode)
 {
     if (AdnInventorUtilities.InvApplication.Documents.Count == 0)
     {
         RefreshControl();
     }
     HandlingCode = HandlingCodeEnum.kEventHandled;
 }
예제 #28
0
 void appEvents_OnDeactivateDocument(_Document documentObject, EventTimingEnum beforeOrAfter, NameValueMap context, out HandlingCodeEnum handlingCode)
 {
     handlingCode = HandlingCodeEnum.kEventNotHandled;
     if (beforeOrAfter == EventTimingEnum.kBefore)
     {
         ResetOnDocumentDeactivate();
     }
 }
 private void onChange(_Document DocumentObject, EventTimingEnum BeforeOrAfter, CommandTypesEnum ReasonsForChange, NameValueMap Context, out HandlingCodeEnum HandlingCode)
 {
     if (BeforeOrAfter == EventTimingEnum.kAfter)
     {
         startMarking(DocumentObject);
     }
     HandlingCode = HandlingCodeEnum.kEventNotHandled;
 }
예제 #30
0
 void appEvents_OnActivateDocument(_Document documentObject, EventTimingEnum beforeOrAfter, NameValueMap context, out HandlingCodeEnum handlingCode)
 {
     handlingCode = HandlingCodeEnum.kEventNotHandled;
     if (beforeOrAfter == EventTimingEnum.kAfter)
     {
         //PersistenceManager.ResetOnDocumentActivate(documentObject);
     }
 }
 private void onClosing(_Document DocumentObject, string FullDocumentName, EventTimingEnum BeforeOrAfter, NameValueMap Context, out HandlingCodeEnum HandlingCode)
 {
     if (BeforeOrAfter == EventTimingEnum.kBefore)
     {
         startUnMarking(DocumentObject);
     }
     HandlingCode = HandlingCodeEnum.kEventNotHandled;
 }
예제 #32
0
 private void Clean()
 {
     if (oDoc != null)
     {
         oDoc.Close(ref oFalse, ref missing, ref missing);
     }
     oDoc = oWord.Documents.Add(ref missing, ref missing,
                                ref missing, ref missing);
 }
예제 #33
0
 private static void CheckSomeBoxesFromBool(_Document doc, FieldInfo info, BoolAttribute attr, Person anketa)
 {
     var templateStr = attr.TemplateString;
     var val = Convert.ToBoolean(info.GetValue(anketa));
     for (var i = 0; i <= 1; i++)
     {
         object strToFindObj = templateStr + i;
         ReplaceString(doc, ((val && i == 1) || (!val && i == 0)) ? "X" : EmptyBox, strToFindObj);
     }
 }
예제 #34
0
 private static void CheckSomeBoxes(_Document doc, FieldInfo info, EnumAttribute attr, Person anketa)
 {
     var templateStr = attr.TemplateString;
     var val = Convert.ToInt32(info.GetValue(anketa)) + 1;
     for (var i = 1; i <= attr.EnumValues; i++)
     {
         object strToFindObj = templateStr + i;
         ReplaceString(doc, i == val ? "X" : EmptyBox, strToFindObj);
     }
 }
예제 #35
0
파일: PreformWord.cs 프로젝트: MadIHI/Test
        //打开文件
        public void OpenDocFile(string docName)
        {
            wordApp = new ApplicationClass();
            wordApp.Visible = false; //所打开的WORD程序,是否是可见的。

            object docObject = docName;  //由于COM操作中,都是使用的 object ,所以,需要做一些转变                       
            if (File.Exists(docName))   // 如果要打开的文件名存在,那就使用doc来打开 
            {
                wordDoc = wordApp.Documents.Add(ref docObject, ref missing, ref missing, ref missing);
                wordDoc.Activate();   //将当前文件设定为活动文档
            }
        }
        private static void addBookmarkToEveryPage(_Application wdApp, _Document doc)
        {
            object unitWdStory = WdUnits.wdStory;
            object oFalse = false;
            object pageBkm = "\\Page";
            object gotoWdGoToPage = WdGoToItem.wdGoToPage;
            object gotoWdGoToNext = WdGoToDirection.wdGoToNext;
            object gotoCount1 = 1;
            object oCollapseStart = WdCollapseDirection.wdCollapseStart;
            object missing = System.Reflection.Missing.Value;

            Selection sel = wdApp.Selection;
            sel.HomeKey(ref unitWdStory, ref oFalse); //Start of doc
            //Assign entire page to range
            Range rngPage = sel.Bookmarks.get_Item(ref pageBkm).Range;
            //We need a second, independent object so that we can later
            //compare the two objects
            Range rngBkm = rngPage.Duplicate;
            //Collapse the second object to a point
            //(will be bookmark location, at top of page)
            rngBkm.Collapse(ref oCollapseStart);
            int counter = 0;
            int lNumPages = (int)sel.get_Information(WdInformation.wdNumberOfPagesInDocument);
            string pageNr = null;

            //Execute at least once,
            //then as long as the last bookmark isn't on the page with the cursor
            // (when can't go to next page, not error occurs, selection stays on last page)
            while (counter == 0 || !rngBkm.InRange(rngPage))
            {
                counter++;
                rngPage.Collapse(ref oCollapseStart);
                //Extra security against an infinite loop
                if (counter > lNumPages) break;
                //Determine the page number
                pageNr = sel.get_Information(WdInformation.wdActiveEndPageNumber).ToString();
                rngBkm = rngPage.Duplicate;
                object oRngBkm = rngBkm;
                //Add a bookmark
                rngPage.Bookmarks.Add("bkmPage" + pageNr, ref oRngBkm);
                //Go to the next page
                sel.GoTo(ref gotoWdGoToPage, ref gotoWdGoToNext, ref gotoCount1, ref missing);
                //Get the full page, for the comparison at the top of the loop
                rngPage = sel.Bookmarks.get_Item(ref pageBkm).Range;
            }
        }
예제 #37
0
파일: PreformWord.cs 프로젝트: MadIHI/Test
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     killWinWordProcess();
     wordApp = new Application();
     wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
     wordApp.Visible = true;
     object templateName = filePath;
     for (int i = 1; i <= wordApp.Documents.Count; i++)
     {
         String str = wordApp.Documents[i].FullName.ToString();
         if (str == wordApp.ToString())
         {
             return;
         }
     }
     wordDoc = wordApp.Documents.Open(ref templateName, 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);
 }
예제 #38
0
파일: WordOp.cs 프로젝트: mildrock/wechat
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     try
     {
         KillWinWordProcess();
         _wordApp = new ApplicationClass
         {
             DisplayAlerts = WdAlertLevel.wdAlertsNone,
             Visible = false
         };
         object missing = System.Reflection.Missing.Value;
         object templateName = filePath;
         _wordDoc = _wordApp.Documents.Open(ref templateName, 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 e)
     {
         Log.Debug("CreateNewDocument出错原因:" + e.Message);
     }
 }
 private static void addAllLinks(_Document doc)
 {
     Range rng = doc.Content;
     Find f = rng.Find;
     object oTrue = true;
     object missing = System.Reflection.Missing.Value;
     rng.Find.ClearFormatting();
     rng.Find.Text = "[Ss]lide @[0-9]@>";
     rng.Find.MatchWildcards = true;
     rng.Find.Execute(
      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);
     do
     {
         addLinkToBookmark(rng, doc);
         rng.Find.Execute(
          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);
     //                Console.WriteLine(rng.Text.ToString());
     } while (rng.Find.Found);
 }
예제 #40
0
        private static Table GetAndPutDowSchedule(ScheduleRepository repo, int lessonLength, int dayOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, Faculty faculty, _Document oDoc, object oEndOfDoc, _Application oWord, Table tableToContinue, CancellationToken cToken)
        {
            cToken.ThrowIfCancellationRequested();

            var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, false);

            cToken.ThrowIfCancellationRequested();

            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable;
            var tableRowOffset = 0;

            if (tableToContinue == null)
            {
                oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count);
                oTable.Borders.Enable = 1;
                oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oTable.Range.Font.Size = 10;
                oTable.Range.Font.Bold = 0;

                oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
                float colWidth = 25.64F / schedule.Count;
                for (int i = 0; i < schedule.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth);
                }
            }
            else
            {
                oTable = tableToContinue;
                tableRowOffset = oTable.Rows.Count;

                for (int i = 0; i < 1 + timeList.Count; i++)
                {
                    oTable.Rows.Add();

                    for (int j = 1; j <= 1 + schedule.Count; j++)
                    {
                        oTable.Cell(tableRowOffset + i + 1, j).Borders[WdBorderType.wdBorderDiagonalUp].Visible = false;
                    }
                }
            }

            oTable.Cell(tableRowOffset + 1, 1).Range.Text = Constants.DowLocal[dayOfWeek];
            oTable.Cell(tableRowOffset + 1, 1).Range.Bold = 1;
            oTable.Cell(tableRowOffset + 1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Text = groupName;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Bold = 1;
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                groupColumn++;
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {

                cToken.ThrowIfCancellationRequested();

                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Text = time + " - " +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Bold = 1;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var groupDowTimeLessons = @group.Value[time]
                            .OrderBy(tfd => tfd.Value.Item2.Select(l =>
                                repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min())
                            .ToList();

                        var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                        var subgroupIds = new List<int>();
                        var subGroupOne = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "1");
                        if (subGroupOne != null) subgroupIds.Add(subGroupOne.StudentGroupId);
                        var subGroupTwo = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "2");
                        if (subGroupTwo != null) subgroupIds.Add(subGroupTwo.StudentGroupId);

                        var subgroups = false;

                        var groupIds =
                                groupDowTimeLessons.Select(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId).ToList();
                        if (groupIds.Intersect(subgroupIds).Count() > 0)
                        {
                            subgroups = true;
                        }

                        Table subgroupsTable = null;
                        Table timeTable = null;

                        List<KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>> group1Items = null;
                        if (subGroupOne != null)
                        {
                            group1Items =
                                groupDowTimeLessons.Where(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId == subGroupOne.StudentGroupId).ToList();
                        }

                        List<KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>> group2Items = null;
                        if (subGroupTwo != null)
                        {
                            group2Items =
                                groupDowTimeLessons.Where(
                                    l =>
                                        l.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup
                                            .StudentGroupId == subGroupTwo.StudentGroupId).ToList();
                        }

                        if (subgroups)
                        {
                            subgroupsTable =
                                oDoc.Tables.Add(oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).Range, 1, 2);
                            subgroupsTable.Cell(1, 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            subgroupsTable.Cell(1, 2).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            subgroupsTable.Cell(1, 1).Borders[WdBorderType.wdBorderRight].Visible = true;

                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, subgroupsTable.Cell(1, 1), group1Items, true);

                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, subgroupsTable.Cell(1, 2), group2Items, true);
                        }
                        else
                        {
                            PutDowSchedulePutGroupOrSubGroupDowTimeItem(repo, oDoc, oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex), groupDowTimeLessons, false);
                        }
                    }

                    columnGroupIndex++;
                }

                timeRowIndex++;
            }

            return oTable;
        }
예제 #41
0
파일: Report.cs 프로젝트: eseawind/YCJN
 //通过模板创建新文档
 public void CreateNewDocument(string filePath)
 {
     killWinWordProcess();
     wordApp = new ApplicationClass();
     wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
     wordApp.Visible = false;
     object missing = System.Reflection.Missing.Value;
     object templateName = filePath;
     wordDoc = wordApp.Documents.Open(ref templateName, 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);
 }
예제 #42
0
        private static void ReplaceString(_Document doc, object replaceStrObj, object strToFindObj)
        {
            object replaceTypeObj = WdReplace.wdReplaceAll;

            for (var i = 1; i <= doc.Sections.Count; i++)
            {
                var wordRange = doc.Sections[i].Range;

                var wordFindObj = wordRange.Find;
                var wordFindParameters = new[]
                                             {
                                                 strToFindObj, _missingObj, _missingObj, _missingObj, _missingObj,
                                                 _missingObj,
                                                 _missingObj, _missingObj, _missingObj, replaceStrObj, replaceTypeObj,
                                                 _missingObj, _missingObj, _missingObj, _missingObj
                                             };

                wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj,
                                                   wordFindParameters);
            }
        }
예제 #43
0
 void appEvents_OnActivateDocument(_Document documentObject, EventTimingEnum beforeOrAfter, NameValueMap context, out HandlingCodeEnum handlingCode)
 {
     handlingCode = HandlingCodeEnum.kEventNotHandled;
     if (beforeOrAfter == EventTimingEnum.kAfter)
     {
         //PersistenceManager.ResetOnDocumentActivate(documentObject);
     }         
 }
예제 #44
0
 void appEvents_OnDeactivateDocument(_Document documentObject, EventTimingEnum beforeOrAfter, NameValueMap context, out HandlingCodeEnum handlingCode)
 {
     handlingCode = HandlingCodeEnum.kEventNotHandled;
     if (beforeOrAfter == EventTimingEnum.kBefore)
     {
         //I think it is probably not necessary to register these events as the registration will happen on its own in InventorServices.
         //PersistenceManager.ResetOnDocumentDeactivate(); 
     }       
 }
            internal static _Document GetObject(MfsOperations parent)
            {
                if (_theObject == null) {
                    _theObject = new _Document (parent);
                }

                return _theObject;
            }
예제 #46
0
 void documentOpen(_Document Doc)
 {
     ThisAddIn.The.sendStringMessage("Word.DocumentOpenEvent " + Doc.Name);
     this.document = Doc;
 }
예제 #47
0
파일: BuildWord.cs 프로젝트: Brinews/Code
 public void NewWordDoc()
 {
     try
     {
         this._wordApp = new ApplicationClass();
         Object myNull = System.Reflection.Missing.Value;
         this._wordDoc = this._wordApp.Documents.Add(ref myNull, ref myNull, ref myNull, ref myNull);
     }
     catch (Exception e)
     {
         Logger.WriteLog("Create Word: " + e.Message);
     }
 }
 public void Dispose()
 {
     _theObject = null;
 }
예제 #49
0
 private static void AddPara(_Document oDoc, string text, int size = 10, int bold = 0, WdLineSpacing spacing = WdLineSpacing.wdLineSpaceSingle, WdParagraphAlignment alignment = WdParagraphAlignment.wdAlignParagraphCenter)
 {
     Paragraph oPara1 = oDoc.Content.Paragraphs.Add();
     oPara1.Range.Text = text;
     oPara1.Range.Font.Bold = 0;
     oPara1.Range.Font.Size = 10;
     oPara1.Range.ParagraphFormat.LineSpacingRule =
         WdLineSpacing.wdLineSpaceSingle;
     oPara1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
     oPara1.SpaceAfter = 0;
     oPara1.Range.InsertParagraphAfter();
 }
        public void InputWord(string url)
        {
            Random rd = new Random();
            int rdd = rd.Next(10, 100);
            string filename = "rs"+DateTime.Now.ToString("yyyy-MM-dd") + rdd.ToString() + ".doc";
            string LocalPath = null;
            //string pdfurl=null;
            try
            {
                int poseuqlurl = url.IndexOf('=');
                int possnap;
                string url1;
                string pdfname;
                url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1);
                possnap = url1.LastIndexOf('/');
                pdfname = url1.Substring(possnap + 1, url1.Length - possnap - 1);
                filename = pdfname;
                /*int poseuqlurl = url.IndexOf('=');
                string url1;
                url1 = url.Substring(poseuqlurl + 1, url.Length - poseuqlurl - 1);
                //pdfurl;*/
                Uri u = new Uri(url1);
                //Uri u = new Uri(url);
                //filename = "123.doc";
                //string time1 = DateTime.Now.ToString();
                //filename = DateTime.Now.ToString() + ".doc";
                LocalPath = "D:\\files\\" + filename;
                if (!File.Exists(@LocalPath))
                {
                    //不存在
                    HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                    mRequest.Method = "GET";
                    mRequest.ContentType = "application/x-www-form-urlencoded";

                    HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();
                    Stream sIn = wr.GetResponseStream();
                    FileStream fs = new FileStream(LocalPath, FileMode.Create, FileAccess.Write);
                    byte[] bytes = new byte[4096];
                    int start = 0;
                    int length;
                    while ((length = sIn.Read(bytes, 0, 4096)) > 0)
                    {
                        fs.Write(bytes, 0, length);
                        start += length;
                    }
                    sIn.Close();
                    wr.Close();
                    fs.Close();
                    string pdfpath = showwordfiles(LocalPath);
                }
            }
            catch { }
            //LocalPath = "D:\\1111.doc";
            delet_tables(LocalPath);
            FileInfo fi = new FileInfo(LocalPath);
            fi.Attributes = FileAttributes.ReadOnly;

            //然后完成对文档的解析

            _Application app = new Microsoft.Office.Interop.Word.Application();
            _Application app1 = new Microsoft.Office.Interop.Word.Application();
            _Application app2 = new Microsoft.Office.Interop.Word.Application();
            _Application app3 = new Microsoft.Office.Interop.Word.Application();
            _Application app4 = new Microsoft.Office.Interop.Word.Application();
            _Application app5 = new Microsoft.Office.Interop.Word.Application();
            _Application app6 = new Microsoft.Office.Interop.Word.Application();
            _Application app7 = new Microsoft.Office.Interop.Word.Application();
            //_Document doc;

            //string temp;
            //type1 = "SyRS";
            //type2 = "TSP";
            //string pattern1 = @"...-SyRS-....";
            //pattern1 = @"^\[\w+-\w+-\w+-\d+\]";
            //pattern2 = @"\[\w+-\w+-\d+\]";
            pattern1 = @"^\[\w{3,}-.+\]";
            pattern2 = @"\[\w{3,}-.+?\]";
            /*pattern1 = @"^\[\w+-\w+-\d+\]";
            pattern2 = @"\[\w+-\w+-\d+\]";*/
            pattern3 = @"End";
            pattern4 = @"^#";
            //string pattern5 = @"[*]";

            //object fileName = @"D:\\projectfiles\cascofiles\testdoc.doc"
            //E:\\cascofiles\testdoc.doc
            object fileName = LocalPath;
            // if (dlg.ShowDialog() == DialogResult.OK)
            //  {
            //     fileName = dlg.FileName;
            //  }
            object unknow = System.Type.Missing;
            //object unknow1 = System.Reflection.Missing.Value;
            doc = app.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc1 = app1.Documents.Open(ref fileName,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
               ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc2 = app2.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc3 = app3.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc4 = app4.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc5 = app5.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc6 = app6.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            doc7 = app7.Documents.Open(ref fileName,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            pcount = doc.Paragraphs.Count;//count the paragraphs
            int jjj = pcount;

            //Thread t1 = new Thread(new ThreadStart(thread1));
            //Thread t2 = new Thread(new ThreadStart(thread2));
            var t1 = new System.Threading.Tasks.Task(() => thread1());
            var t2 = new System.Threading.Tasks.Task(() => thread2());
            var t3 = new System.Threading.Tasks.Task(() => thread3());
            var t4 = new System.Threading.Tasks.Task(() => thread4());
            var t5 = new System.Threading.Tasks.Task(() => thread5());
            var t6 = new System.Threading.Tasks.Task(() => thread6());
            var t7 = new System.Threading.Tasks.Task(() => thread7());
            var t8 = new System.Threading.Tasks.Task(() => thread8());
            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();
            t5.Start();
            t6.Start();
            t7.Start();
            t8.Start();
            System.Threading.Tasks.Task.WaitAll(t1,t2,t3,t4,t5,t6,t7,t8);
            doc.Close(ref unknow, ref unknow, ref unknow);

            doc1.Close(ref unknow, ref unknow, ref unknow);

            doc2.Close(ref unknow, ref unknow, ref unknow);

            doc3.Close(ref unknow, ref unknow, ref unknow);

            doc4.Close(ref unknow, ref unknow, ref unknow);

            doc5.Close(ref unknow, ref unknow, ref unknow);

            doc6.Close(ref unknow, ref unknow, ref unknow);

            doc7.Close(ref unknow, ref unknow, ref unknow);

            app.Quit(ref unknow, ref unknow, ref unknow);
            app1.Quit(ref unknow, ref unknow, ref unknow);
            app2.Quit(ref unknow, ref unknow, ref unknow);
            app3.Quit(ref unknow, ref unknow, ref unknow);
            app4.Quit(ref unknow, ref unknow, ref unknow);
            app5.Quit(ref unknow, ref unknow, ref unknow);
            app6.Quit(ref unknow, ref unknow, ref unknow);
            app7.Quit(ref unknow, ref unknow, ref unknow);
            //string jsonString = string1+string2+string3+string4+string5+string6+string7+string8;
            var json = new JavaScriptSerializer().Serialize(aaa.finalstrings);
            //jsonString = string1;
            //return myarray[0].arraycontent[5];
            Context.Response.ContentType = "text/json";
            Context.Response.Write(json);
            Context.Response.End();
            //return jsonString;
            //return myarray[0].sourse[0];
            //return "123";
        }
 /// <summary>
 /// Event handler for the execute event. This method is effectively what gets called from the Connect method
 /// and simply passes execution right along to the parent class
 /// </summary>
 /// <param name="Document"></param>
 /// <param name="Context"></param>
 /// <param name="Succeeded"></param>
 void changeProcessor_OnExecute(_Document Document, NameValueMap Context, ref bool Succeeded)
 {
     _parentClass.ChangeProcessor_OnExecute(Document, Context, ref Succeeded);
 }
        public string readtitles(string filename)
        {
            _Application app = new Microsoft.Office.Interop.Word.Application();
            _Document doc;

            object fileName = filename;
            object unknow = System.Type.Missing;
            doc = app.Documents.Open(ref fileName,
                           ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                           ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                           ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//input a doc
            object pcount = doc.Paragraphs.Count;//count the paragraphs
            object trydocfunc = doc.Tables.Count;
            object listnumbers = doc.Lists.Count;
            object listpnumbers = doc.ListParagraphs.Count;
            object listtbumbers = doc.ListTemplates.Count;
            Lists lists = doc.Lists;
            ListParagraphs listps = doc.ListParagraphs;
            ListTemplates listts = doc.ListTemplates;
            object list1 = lists[1];
            object list2 = lists[2];
            object list3 = listps[1];
            object list4 = listts[1];
            string k = listps[3].Range.Text.Trim();
            //object level = lists[1].ApplyListTemplateWithLevel
            string[] k3 = new string[3];
            for (int i = 0; i <= 1; i++)
            {
                k3[i] = lists[i + 1].Range.Text.Trim();
            }
            int[] num3 = new int[2];
            for (int i = 0; i <= 1; i++)
            {
                num3[i] = lists[i + 1].Range.Start;
            }
            string[] k4 = new string[3];
            for (int i = 0; i <= 2; i++)
            {
                k3[i] = listps[i + 1].Range.Text.Trim();
            }
            listpnumbers = doc.ListParagraphs.Count;
            app.Documents.Close(ref unknow, ref unknow, ref unknow);
            app.Quit(ref unknow, ref unknow, ref unknow);
            return null;
        }
예제 #53
0
 /// <summary>
 /// Save a Microsoft Word Document as PDF
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="outputFileName"></param>
 public void SaveWordDocumentAsPdf(_Document doc, String outputFileName)
 {
     doc.ExportAsFixedFormat(outputFileName,
         PdfExportParams.ExportFormat, PdfExportParams.OpenAfterExport, PdfExportParams.OptimizeFor,
         PdfExportParams.ExportRange, PdfExportParams.StartPage, PdfExportParams.EndPage,
         PdfExportParams.ExportItem, PdfExportParams.IncludeDocProps, PdfExportParams.KeepIRM,
         PdfExportParams.CreateBookmarks, PdfExportParams.DocStructureTags, PdfExportParams.BitmapMissingFonts,
         PdfExportParams.UseISO19005_1, PdfExportParams.FixedFormatExtClassPtr
     );
 }
예제 #54
0
        private static Table GetAndPutDowStartSchedule(ScheduleRepository repo, int lessonLength, int dayOfWeek, bool weekFiltered, int weekFilter, bool weeksMarksVisible, Faculty faculty, _Document oDoc, object oEndOfDoc, _Application oWord, CancellationToken cToken)
        {
            cToken.ThrowIfCancellationRequested();

            var schedule = repo.Lessons.GetFacultyDowSchedule(faculty.FacultyId, dayOfWeek, weekFiltered, weekFilter, false, false);

            cToken.ThrowIfCancellationRequested();

            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + (schedule.Count * 2));
            oTable.Borders.Enable = 1;
            oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
            oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            oTable.Range.Font.Size = 11;
            oTable.Range.Font.Bold = 0;

            oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
            float colWidth = 25.64F / schedule.Count;
            for (int i = 0; i < schedule.Count * 2; i += 2)
            {
                oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth - 1.1f);
                oTable.Columns[i + 3].Width = oWord.CentimetersToPoints(1.1f);
            }

            oTable.Range.Font.Underline = WdUnderline.wdUnderlineNone;

            oTable.Cell(1, 1).Range.Text = "Время занятий";//Constants.DOWLocal[dayOfWeek];
            oTable.Cell(1, 1).Range.Font.Bold = 1;
            oTable.Cell(1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;
                oTable.Cell(1, groupColumn).Range.Text = groupName;
                oTable.Cell(1, groupColumn).Range.Font.Bold = 1;
                oTable.Cell(1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(1, groupColumn).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                oTable.Cell(1, groupColumn + 1).Range.Text = "Ауд";
                oTable.Cell(1, groupColumn + 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                groupColumn += 2;
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {
                cToken.ThrowIfCancellationRequested();

                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(timeRowIndex, 1).Range.Text = time + "-" +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(timeRowIndex, 1).Range.Font.Bold = 1;
                oTable.Cell(timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var groupDowTimeLessons = @group.Value[time]
                            .OrderBy(tfd => tfd.Value.Item2.Select(l =>
                                repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min())
                            .ToList();
                        var tfdIndex = 0;

                        if (groupDowTimeLessons.Count() == 2)
                        {
                            if (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.") &&
                                groupDowTimeLessons[1].Value.Item1.Contains("(нечёт."))
                            {
                                var tmp = groupDowTimeLessons[0];
                                groupDowTimeLessons[0] = groupDowTimeLessons[1];
                                groupDowTimeLessons[1] = tmp;
                            }
                        }

                        if (
                            ((@group.Value[time].Count == 2) &&
                            ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                            || ((@group.Value[time].Count == 1) && (groupDowTimeLessons[0].Value.Item1.Contains("чёт."))))
                        {
                            var rng = oTable.Cell(timeRowIndex, columnGroupIndex).Range;
                            rng.Borders[WdBorderType.wdBorderDiagonalUp].LineStyle = WdLineStyle.wdLineStyleSingle;
                        }

                        var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                        var subGroupOne = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "1");
                        var subGroupTwo = repo.StudentGroups.GetFirstFiltredStudentGroups(sg => sg.Name == groupObject.Name + "2");

                        if (groupDowTimeLessons.Count() == 2)
                        {
                            if (((subGroupOne != null) && (subGroupTwo != null)) &&
                                ((groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupTwo.StudentGroupId) &&
                                 (groupDowTimeLessons[1].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupOne.StudentGroupId)))
                            {
                                var tmp = groupDowTimeLessons[0];
                                groupDowTimeLessons[0] = groupDowTimeLessons[1];
                                groupDowTimeLessons[1] = tmp;
                            }
                        }

                        var addSubGroupColumn = 0;

                        if ((groupDowTimeLessons.Count() == 1) &&
                            (subGroupOne != null) &&
                            (groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupOne.StudentGroupId))
                        {
                            addSubGroupColumn = 1;

                            var emptytfd = new KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>(-1, null);
                            groupDowTimeLessons.Add(emptytfd);
                        }

                        if ((groupDowTimeLessons.Count() == 1) &&
                            (subGroupTwo != null) &&
                            (groupDowTimeLessons[0].Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId == subGroupTwo.StudentGroupId))
                        {
                            addSubGroupColumn = 1;

                            var emptytfd = new KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>(-1, null);
                            groupDowTimeLessons.Add(emptytfd);

                            var tmp = groupDowTimeLessons[0];
                            groupDowTimeLessons[0] = groupDowTimeLessons[1];
                            groupDowTimeLessons[1] = tmp;
                        }

                        var timeTable = oDoc.Tables.Add(oTable.Cell(timeRowIndex, columnGroupIndex).Range, 1, @group.Value[time].Count + addSubGroupColumn);

                        if (!((groupDowTimeLessons.Count == 2) &&
                            (((groupDowTimeLessons[0].Value != null) && (groupDowTimeLessons[1].Value != null)) &&
                             ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))))
                        {
                            for (int i = 0; i < groupDowTimeLessons.Count - 1; i++)
                            {
                                timeTable.Cell(1, i + 1).Borders[WdBorderType.wdBorderRight].Visible = true;
                            }
                        }

                        timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                        timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        timeTable.Range.Font.Size = 10;
                        timeTable.Range.Font.Bold = 0;

                        foreach (var tfdData in groupDowTimeLessons)
                        {
                            var cellText = "";

                            if (tfdData.Value == null)
                            {
                                tfdIndex++;

                                continue;
                            }

                            var discName = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;

                            var shorteningDictionary = new Dictionary<string, string>
                            {
                                {"Английский язык", "Англ. яз."},
                                {"Немецкий язык", "Нем. яз."},
                                {"Французский язык", "Франц. яз."}
                            };

                            if (shorteningDictionary.ContainsKey(discName))
                            {
                                discName = shorteningDictionary[discName];
                            }

                            // Discipline name
                            cellText += discName + Environment.NewLine;

                            // Teacher FIO
                            var ommitInitials = @group.Value[time].Count != 1;
                            String teacherFio = ShortenFio(tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO, ommitInitials);
                            cellText += teacherFio;

                            // Total weeks
                            if (weeksMarksVisible)
                            {
                                /*
                                if (tfdData.Value.Item1.Contains("(чёт."))
                                {
                                    cellText += "(чёт.)" + Environment.NewLine;
                                }
                                if (tfdData.Value.Item1.Contains("(нечёт."))
                                {
                                    cellText += "(нечёт.)" + Environment.NewLine;
                                }
                                */
                                //cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine;
                            }

                            String audText = "";
                            // Auditoriums
                            var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date),
                                l => l.Item1.Auditorium.Name);
                            var grouped = audWeekList.GroupBy(a => a.Value);

                            var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList();
                            var gcount = enumerable.Count();
                            if (gcount == 1)
                            {
                                audText += ShortenAudName(enumerable.ElementAt(0).Key);
                            }
                            else
                            {
                                for (int j = 0; j < gcount; j++)
                                {
                                    var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                                    audText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " +
                                               ShortenAudName(jItem.Key);

                                    if (j != gcount - 1)
                                    {
                                        audText += Environment.NewLine;
                                    }
                                }
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.")))
                            {
                                cellText = Environment.NewLine + cellText;
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(нечёт.")))
                            {
                                cellText = cellText + Environment.NewLine;
                            }
                            //Auditoriums

                            timeTable.Cell(1, tfdIndex + 1).Range.Text = cellText;
                            timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                WdParagraphAlignment.wdAlignParagraphCenter;

                            /*
                             * FIO in one line
                            var lineSpacing = timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.LineSpacing;

                            var Height = timeTable.Cell(1, tfdIndex + 1).Height;

                            if (Height > lineSpacing * 2)
                            {

                            }
                             */

                            timeTable.Cell(1, tfdIndex + 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            var audCellText = oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text;
                            if (audCellText == "\r\a")
                            {
                                oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text = audText;
                            }
                            else
                            {
                                oTable.Cell(timeRowIndex, columnGroupIndex + 1).Range.Text = audCellText + "/ " + audText;
                            }

                            oTable.Cell(timeRowIndex, columnGroupIndex + 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            if ((@group.Value[time].Count == 2) &&
                                ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) && (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                            {
                                timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                    (tfdIndex == 0)
                                        ? WdParagraphAlignment.wdAlignParagraphLeft
                                        : WdParagraphAlignment.wdAlignParagraphRight;
                            }

                            if ((groupDowTimeLessons.Count == 1) &&
                                (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.")))
                            {
                                timeTable.Cell(1, tfdIndex + 1).Range.ParagraphFormat.Alignment =
                                    WdParagraphAlignment.wdAlignParagraphRight;
                            }

                            tfdIndex++;
                        }
                    }

                    columnGroupIndex += 2;
                }

                timeRowIndex++;
            }

            return oTable;
        }
예제 #55
0
        private static Table PutDayScheduleInWord(ScheduleRepository repo, int lessonLength, bool weeksMarksVisible,
            Dictionary<int, Dictionary<string, Dictionary<int, Tuple<string, List<Tuple<Lesson, int>>, string>>>> schedule, _Document oDoc, object oEndOfDoc, _Application oWord, Table table, int dayOfWeek)
        {
            var timeList = new List<string>();
            foreach (var group in schedule)
            {
                foreach (var time in @group.Value.Keys)
                {
                    if (!timeList.Contains(time))
                    {
                        timeList.Add(time);
                    }
                }
            }

            Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            Table oTable;

            var plainGroupsListIds = new Dictionary<int, List<int>>();
            var nGroupsListIds = new Dictionary<int, List<int>>();
            var plainNGroupIds = new Dictionary<int, Tuple<int, int>>();

            int tableRowOffset = 0;

            if (table != null)
            {
                oTable = table;
                tableRowOffset = oTable.Rows.Count;

                for (int i = 0; i < 1 + timeList.Count; i++)
                {
                    oTable.Rows.Add();
                }
            }
            else
            {

                oTable = oDoc.Tables.Add(wrdRng, 1 + timeList.Count, 1 + schedule.Count);
                oTable.Borders.Enable = 1;
                oTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                oTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                oTable.Range.Font.Size = 10;
                oTable.Range.Font.Bold = 0;

                oTable.Columns[1].Width = oWord.CentimetersToPoints(2.44f);
                float colWidth = 25.64F / schedule.Count;
                for (int i = 0; i < schedule.Count; i++)
                {
                    oTable.Columns[i + 2].Width = oWord.CentimetersToPoints(colWidth);
                }
            }

            oTable.Cell(tableRowOffset + 1, 1).Range.Text = Constants.DowLocal[dayOfWeek];
            oTable.Cell(tableRowOffset + 1, 1).Range.ParagraphFormat.Alignment =
                WdParagraphAlignment.wdAlignParagraphCenter;

            int groupColumn = 2;

            foreach (var group in schedule)
            {
                var groupObject = repo.StudentGroups.GetStudentGroup(@group.Key);
                var groupName = groupObject.Name;

                oTable.Cell(tableRowOffset + 1, groupColumn).Range.Text = groupName.Replace(" (+Н)", "");
                oTable.Cell(tableRowOffset + 1, groupColumn).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                groupColumn++;

                if (groupName.Contains(" (+Н)"))
                {
                    var plainGroupName = groupName.Replace(" (+Н)", "");
                    var nGroupName = groupName.Replace(" (+", "(");

                    var plainGroupId = repo.StudentGroups.FindStudentGroup(plainGroupName).StudentGroupId;
                    var plainStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => sig.StudentGroup.StudentGroupId == plainGroupId)
                        .Select(stig => stig.Student.StudentId)
                        .ToList();
                    plainGroupsListIds.Add(@group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => plainStudentIds.Contains(sig.Student.StudentId))
                        .Select(stig => stig.StudentGroup.StudentGroupId)
                        .Distinct()
                        .ToList());

                    var nGroupId = repo.StudentGroups.FindStudentGroup(nGroupName).StudentGroupId;
                    var nStudentIds = repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => sig.StudentGroup.StudentGroupId == nGroupId)
                        .Select(stig => stig.Student.StudentId)
                        .ToList();
                    nGroupsListIds.Add(@group.Key, repo.StudentsInGroups.GetAllStudentsInGroups()
                        .Where(sig => nStudentIds.Contains(sig.Student.StudentId))
                        .Select(stig => stig.StudentGroup.StudentGroupId)
                        .Distinct()
                        .ToList());

                    plainNGroupIds.Add(groupObject.StudentGroupId, new Tuple<int, int>(plainGroupId, nGroupId));
                }
            }

            var timeRowIndexList = new List<int>();

            var timeRowIndex = 2;
            foreach (var time in timeList.OrderBy(t => int.Parse(t.Split(':')[0]) * 60 + int.Parse(t.Split(':')[1])))
            {
                var hour = int.Parse(time.Substring(0, 2));
                var minute = int.Parse(time.Substring(3, 2));

                minute += lessonLength;

                while (minute >= 60)
                {
                    hour++;
                    minute -= 60;
                }

                timeRowIndexList.Add(timeRowIndex);
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.Text = time + " - " +
                                                          hour.ToString("D2") + ":" + minute.ToString("D2");
                oTable.Cell(tableRowOffset + timeRowIndex, 1).Range.ParagraphFormat.Alignment =
                    WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Cell(tableRowOffset + timeRowIndex, 1).VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                var columnGroupIndex = 2;
                foreach (var group in schedule)
                {
                    if (@group.Value.ContainsKey(time))
                    {
                        oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).VerticalAlignment =
                            WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                        var timeTable = oDoc.Tables.Add(oTable.Cell(tableRowOffset + timeRowIndex, columnGroupIndex).Range, 1, 1);
                        for (int i = 0; i < @group.Value[time].Count - 1; i++)
                        {
                            timeTable.Rows.Add();
                        }
                        for (int i = 0; i < @group.Value[time].Count - 1; i++)
                        {
                            timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;
                        }
                        timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
                        timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                        timeTable.Range.Font.Size = 10;
                        timeTable.Range.Font.Bold = 0;

                        var tfdIndex = 0;
                        foreach (
                            var tfdData in
                                @group.Value[time].OrderBy(
                                    tfd => tfd.Value.Item2.Select(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date)).Min()))
                        {
                            var cellText = "";
                            // Discipline name
                            cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;

                            // N + Group modifiers
                            var groupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if (plainGroupsListIds.ContainsKey(@group.Key))
                            {
                                if (plainGroupsListIds[@group.Key].Contains(groupId) &&
                                    nGroupsListIds[@group.Key].Contains(groupId))
                                {
                                    cellText += " (+Н)";
                                }
                                if (!plainGroupsListIds[@group.Key].Contains(groupId) &&
                                    nGroupsListIds[@group.Key].Contains(groupId))
                                {
                                    cellText += " (Н)";
                                }
                            }

                            var tfdGroupId = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.StudentGroupId;
                            if ((tfdGroupId != @group.Key))
                            {
                                if ((!plainNGroupIds.ContainsKey(@group.Key)) ||
                                    ((tfdGroupId != plainNGroupIds[@group.Key].Item1) &&
                                     (tfdGroupId != plainNGroupIds[@group.Key].Item2)))
                                {
                                    cellText += " (" + tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.StudentGroup.Name +
                                                ")";
                                }
                            }

                            cellText += Environment.NewLine;
                            // Teacher FIO
                            cellText += tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO + Environment.NewLine;

                            // Total weeks
                            if (weeksMarksVisible)
                            {
                                cellText += "(" + tfdData.Value.Item1 + ")" + Environment.NewLine;
                            }

                            var audWeekList = tfdData.Value.Item2.ToDictionary(l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date),
                                l => l.Item1.Auditorium.Name);
                            var grouped = audWeekList.GroupBy(a => a.Value);

                            var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ?? grouped.ToList();
                            var gcount = enumerable.Count();
                            if (gcount == 1)
                            {
                                cellText += enumerable.ElementAt(0).Key;
                            }
                            else
                            {
                                for (int j = 0; j < gcount; j++)
                                {
                                    var jItem = enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                                    cellText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) + " - " +
                                                jItem.Key;

                                    if (j != gcount - 1)
                                    {
                                        cellText += Environment.NewLine;
                                    }
                                }
                            }

                            timeTable.Cell(tfdIndex + 1, 1).Range.Text = cellText;
                            timeTable.Cell(tfdIndex + 1, 1).VerticalAlignment =
                                WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                            tfdIndex++;
                        }
                    }

                    columnGroupIndex++;
                }

                timeRowIndex++;
            }
            return oTable;
        }
예제 #56
0
        private static void PutDowSchedulePutGroupOrSubGroupDowTimeItem(ScheduleRepository repo, _Document oDoc, Cell tableCell, List<KeyValuePair<int, Tuple<string, List<Tuple<Lesson, int>>, string>>> groupDowTimeLessons, bool subgroups)
        {
            Table timeTable = oDoc.Tables.Add(tableCell.Range, 1, 1);
            for (int i = 0; i < groupDowTimeLessons.Count - 1; i++)
            {
                timeTable.Rows.Add();
            }

            if (!((groupDowTimeLessons.Count == 2) &&
                  ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) &&
                   (groupDowTimeLessons[1].Value.Item1.Contains("чёт.")))))
            {
                for (int i = 0; i < groupDowTimeLessons.Count - 1; i++)
                {
                    timeTable.Cell(i + 1, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;
                }
            }

            timeTable.Range.ParagraphFormat.SpaceAfter = 0.0F;
            timeTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
            timeTable.Range.Font.Size = 10;
            timeTable.Range.Font.Bold = 0;

            if (groupDowTimeLessons.Count == 2)
            {
                if (((groupDowTimeLessons[0].Value != null) && (groupDowTimeLessons[1].Value != null)) &&
                    (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.") &&
                     groupDowTimeLessons[1].Value.Item1.Contains("(нечёт.")))
                {
                    var tmp = groupDowTimeLessons[0];
                    groupDowTimeLessons[0] = groupDowTimeLessons[1];
                    groupDowTimeLessons[1] = tmp;
                }
            }

            if (
                ((groupDowTimeLessons.Count == 2) &&
                 ((groupDowTimeLessons[0].Value != null) && (groupDowTimeLessons[1].Value != null)) &&
                 ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) &&
                  (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                || ((groupDowTimeLessons.Count == 1) &&
                    (groupDowTimeLessons[0].Value != null) &&
                    (groupDowTimeLessons[0].Value.Item1.Contains("чёт."))))
            {
                tableCell.Range.Borders[WdBorderType.wdBorderDiagonalUp].LineStyle = WdLineStyle.wdLineStyleSingle;
            }

            for (int dowTimeIndex = 0; dowTimeIndex < groupDowTimeLessons.Count; dowTimeIndex++)
            {
                var tfdData = groupDowTimeLessons[dowTimeIndex];
                var cellText = "";

                if (tfdData.Value == null)
                {
                    dowTimeIndex++;

                    continue;
                }

                // Discipline name
                var discName = tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Discipline.Name;

                var shorteningDictionary = new Dictionary<string, string>
                {
                    {"Английский язык", "Англ. яз."},
                    {"Немецкий язык", "Нем. яз."},
                    {"Французский язык", "Франц. яз."}
                };

                if (shorteningDictionary.ContainsKey(discName))
                {
                    discName = shorteningDictionary[discName];
                }

                cellText += discName;
                cellText += Environment.NewLine;

                // Teacher FIO
                string teacherFio = ShortenFio(
                    tfdData.Value.Item2[0].Item1.TeacherForDiscipline.Teacher.FIO,
                    subgroups);
                cellText += teacherFio + Environment.NewLine;

                // Auditoriums
                var audWeekList =
                    tfdData.Value.Item2.ToDictionary(
                        l => repo.CommonFunctions.CalculateWeekNumber(l.Item1.Calendar.Date),
                        l => l.Item1.Auditorium.Name);
                var grouped = audWeekList.GroupBy(a => a.Value);

                var enumerable = grouped as List<IGrouping<string, KeyValuePair<int, string>>> ??
                                 grouped.ToList();
                var gcount = enumerable.Count();
                if (gcount == 1)
                {
                    cellText += enumerable.ElementAt(0).Key;
                }
                else
                {
                    for (int j = 0; j < gcount; j++)
                    {
                        var jItem =
                            enumerable.OrderBy(e => e.Select(ag => ag.Key).ToList().Min()).ElementAt(j);
                        cellText += CommonFunctions.CombineWeeks(jItem.Select(ag => ag.Key).ToList()) +
                                    " - " +
                                    jItem.Key;

                        if (j != gcount - 1)
                        {
                            cellText += Environment.NewLine;
                        }
                    }
                }
                // Auditoriums

                // Extra line on diagonal split
                if (groupDowTimeLessons[dowTimeIndex].Value.Item1.Contains("(чёт."))
                {
                    cellText = Environment.NewLine + cellText;
                }

                if (groupDowTimeLessons[dowTimeIndex].Value.Item1.Contains("(нечёт."))
                {
                    cellText = cellText + Environment.NewLine;
                }
                // Extra line on diagonal split

                var rowIndex = 1 + dowTimeIndex;
                var columnIndex = 1;

                timeTable.Cell(rowIndex, columnIndex).Range.Text = cellText;
                timeTable.Cell(rowIndex, columnIndex).VerticalAlignment =
                    WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                if ((groupDowTimeLessons.Count == 2) &&
                    ((groupDowTimeLessons[0].Value.Item1.Contains("нечёт.")) &&
                     (groupDowTimeLessons[1].Value.Item1.Contains("чёт."))))
                {
                    timeTable.Cell(rowIndex, columnIndex).Range.ParagraphFormat.Alignment =
                        (dowTimeIndex == 0)
                            ? WdParagraphAlignment.wdAlignParagraphLeft
                            : WdParagraphAlignment.wdAlignParagraphRight;
                }

                if ((groupDowTimeLessons.Count == 1) &&
                    (groupDowTimeLessons[0].Value.Item1.Contains("(нечёт.")))
                {
                    tableCell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop;
                }

                    if ((groupDowTimeLessons.Count == 1) &&
                    (groupDowTimeLessons[0].Value.Item1.Contains("(чёт.")))
                {
                    timeTable.Cell(rowIndex, columnIndex).Range.ParagraphFormat.Alignment =
                        WdParagraphAlignment.wdAlignParagraphRight;
                    tableCell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;
                }
            }
        }
예제 #57
0
파일: BuildWord.cs 프로젝트: Brinews/Code
        /// <summary>
        /// 转为PDF
        /// </summary>
        /// <param name="dstDir"></param>
        /// <param name="docFileName"></param>
        /// <returns></returns>
        public Boolean ConvertToPDF(String dstDir, String docFileName)
        {
            string wjm = Path.GetFileNameWithoutExtension(docFileName);
            string path = FormatPath(wjm);

            //该目录存在
            dstDir += path;

            string pdfFile = dstDir + wjm + ".pdf";
            string docFile = dstDir + docFileName;

            WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF;
            bool result;
            object paramMissing = Type.Missing;
            //ApplicationClass wordApplication = new ApplicationClass();
            this._wordApp = new ApplicationClass();

            try
            {
                object paramSourceDocPath = docFile;
                string paramExportFilePath = pdfFile;

                WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                _wordDoc = _wordApp.Documents.Open(
                        ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing, ref paramMissing, ref paramMissing,
                        ref paramMissing);

                if (_wordDoc != null)
                    _wordDoc.ExportAsFixedFormat(paramExportFilePath,
                            paramExportFormat, paramOpenAfterExport,
                            paramExportOptimizeFor, paramExportRange, paramStartPage,
                            paramEndPage, paramExportItem, paramIncludeDocProps,
                            paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                            paramBitmapMissingFonts, paramUseISO19005_1,
                            ref paramMissing);
                result = true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                _wordDoc.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                _wordApp.Quit(ref paramMissing, ref paramMissing, ref paramMissing);

                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }
예제 #58
0
            void m_ApplicationEvents_OnOpenDocument(_Document DocumentObject, string FullDocumentName, EventTimingEnum BeforeOrAfter, NameValueMap Context, out HandlingCodeEnum HandlingCode)
            {
                System.Windows.Forms.MessageBox.Show("OnOpenDocument fires!");

                HandlingCode = HandlingCodeEnum.kEventHandled;
            }
예제 #59
0
 void windowActivate(_Document Doc, Window Wn)
 {
     ThisAddIn.The.sendStringMessage("Word.WindowActivateEvent " + Wn.Caption + "/" + Doc.Name);
     this.document = Doc;
 }
예제 #60
0
        public void createMinutes()
        {
            if (word == null) start();

            try
            {

                if (this.document == null)
                {

                    if (this.Template == "")
                    {
                        //System.Windows.Forms.MessageBox.Show("Minutes template not set, setting to C:\\Devel\\test.dotx", "Warning", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                        //this.Template = "C:\\Devel\\test.dotx";
                        this.Template = "C:\\tmp\\myMeeting.dot"; // quick demo hack

                    }

                    object newTemplate = Missing.Value;	//Not creating a template.
                    object documentType = Missing.Value;	//Plain old text document.
                    object visible = true;		//Show the doc while we work.
                    object template = this.Template;

                    this.document =
                      word.Documents.Add(ref template,
                                            ref newTemplate,
                                            ref documentType,
                                            ref visible);
                }

                // Begin quick demo hack

                object part = "title";
                this.document.Bookmarks.get_Item(ref part).Range.Text = "Cabin Air Condition";
                part = "location";
                this.document.Bookmarks.get_Item(ref part).Range.Text = "HLRS";

                part = "participants";
                List<DocumentPart> participants = this.documentParts["participants"];
                String pString = "";
                foreach (DocumentPart p in participants)
                    pString += p.PartValue + "\n";
                this.document.Bookmarks.get_Item(ref part).Range.Text = pString;

                part = "item";
                this.document.Bookmarks.get_Item(ref part).Range.Text = "Assessing cabin temperatures";

                object optional = Missing.Value;
                object gotoItem = WdGoToItem.wdGoToSection;
                object gotoDirection = WdGoToDirection.wdGoToAbsolute;
                object count = 2;
                word.Selection.GoTo(ref gotoItem, ref gotoDirection, ref count, ref optional);

                List<DocumentPart> snapshots = this.documentParts["snapshot"];
                string path = "";
                foreach (DocumentPart s in snapshots)
                    path += s.PartValue + ";";

                if (path.Length != 0)
                {
                    string sign = ";";
                    char[] delims = sign.ToCharArray();
                    string[] pathlist = path.Split(delims);
                    object tr = Microsoft.Office.Core.MsoTriState.msoTrue;
                    //object fa = Microsoft.Office.Core.MsoTriState.msoFalse;
                    foreach (string s in pathlist)
                    {
                        try
                        {
                            if (s != "")
                                word.Selection.InlineShapes.AddPicture(s, ref tr, ref tr, ref optional);
                        }
                        catch (Exception e)
                        {
                            word.Selection.TypeText(e.Message + ": " + s + "\n");
                        }
                        word.Selection.TypeText("\n");
                    }
                }

                // End quick demo hack

                string date = System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
                string filename = "C:\\Devel\\minutes" + date + ".doc";
                save(filename);
            }
            catch { }
        }