예제 #1
0
        public void WordList()
        {
            HashSet <string> wordlist = new HashSet <string>();

            wordlist = GetWordList();

            //Create new document
            Word.Document  newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Word List\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "This is a proofreading tool. It takes every word in the document, strips the punctuation, removes words that consist only of numbers, and then presents them all in alphabetical order. This is a great way to find typos and inconsistencies.\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "Capitalization is retained as is. That means that words that appear at the beginning of a sentence will appear capitalized.\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(3);

            string[] words = wordlist.ToArray();
            Array.Sort(words);
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = string.Join("\n", words) + "\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
        }
예제 #2
0
        /// <summary>
        /// Moves the focus to the appropriate header/footer.
        /// </summary>
        /// <param name="SelectionRange">The range containing the target header/footer.</param>
        /// <param name="sectionIdFinal">The section to be selected.</param>
        /// <param name="headerFooterId">The header/footer type to be selected.</param>
        internal static void MoveHeaderFooterFocus(Word.Range SelectionRange, int?sectionIdFinal, Word.WdHeaderFooterIndex?headerFooterId)
        {
            if (sectionIdFinal != null && headerFooterId != null)
            {
                Word.Window CurrentWindow = SelectionRange.Application.ActiveWindow;
                try
                {
                    Word.Section CurrentSection = SelectionRange.Document.Sections[(int)sectionIdFinal];
                    if (!RedactCommon.GetHeaderFooterVisibility(CurrentSection, (Word.WdHeaderFooterIndex)headerFooterId) || CurrentWindow.View.Type != Word.WdViewType.wdPrintView)
                    {
                        //if that header/footer isn't being shown, we need to fall back into normal view
                        CurrentWindow.View.Type = Word.WdViewType.wdNormalView;
                        CurrentSection.Range.Select();
                        CurrentWindow.View.SplitSpecial = RedactCommon.GetSplitTypeForStory(SelectionRange.StoryType);
                    }
                    else
                    {
                        //select the appropriate section
                        SelectionRange.Document.Sections[(int)sectionIdFinal].Range.Select();

                        //jump to the header/footer
                        CurrentWindow.View.SeekView = RedactCommon.GetSeekViewForStory(SelectionRange.StoryType);

                        Thread tTabSwitch = new Thread(StayOnReviewTab);
                        tTabSwitch.Start(Redaction.Properties.Resources.ReviewTab);
                    }
                }
                catch (COMException)
                {
                    System.Diagnostics.Debug.Fail("incorrect header/footer view movement detected");
                }
            }
        }
예제 #3
0
        private void cmboAllignSlot_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var app = new Microsoft.Office.Interop.Word.Application();
            var doc = new Microsoft.Office.Interop.Word.Document();

            doc = app.Documents.Add(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx");
            //Hard gecodeerd vanuit template
            Section s = doc.Sections[6];

            //Switch case om de uitlijning correct uit te voeren , Links staat er niet bij omdat dit "default" zo staat.
            switch (cmboAllignSlot.SelectedItem)
            {
            case "Rechts":
                s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                break;

            case "Centreren":
                s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                break;

            default:
                s.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                break;
            }
            doc.SaveAs2(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx");
            doc.Close();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        }
예제 #4
0
        private void WelcomeText_Click(object sender, RoutedEventArgs e)
        {
            //Word app + document aanmaken + instellen in welk document gewerkt word.
            var app = new Microsoft.Office.Interop.Word.Application();
            var doc = new Microsoft.Office.Interop.Word.Document();

            doc = app.Documents.Add(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx");
            //Hard gecodeerde Sectie van template aanspreken.
            Section s = doc.Sections[4];
            //Volledige "Afstand" van sectie bepalen.
            Range r = doc.Sections[4].Range;

            //Controleren of gebruiker zelf iets ingevuld heeft als text
            if (!TxtbxWelkomText.Text.Equals(""))
            {
                r.Text = TxtbxWelkomText.Text.Trim() + "\n\r";
            }
            else
            { //Voor geprogrammeerde text voor alle sportclubs.
                r.Text = "Welkom beste leden bij het begin van het nieuwe jaar, we zijn blij om u nog steeds als lid te zien." +
                         " We hebben natuurlijk nieuwe spullen nodig om het nieuw sportjaar goed in te zetten, dit vind u terug in de tabel hieronder.\n\r";
            }
            //Maken dat de range van de ingetypte woorden niet afkapt. dus zelfs groote instellen
            r.SetRange(0, r.Text.Length);
            //toevoegen als paragraaf
            s.Range.Paragraphs.Add(r);
            //opslaan &sluiten
            doc.SaveAs2(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "/Template1Bewerkt.docx");
            doc.Close();

            //Dit om bepaalde achtergrond taken te stoppen.
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        }
예제 #5
0
        private void CreateDocument()
        {
            Application = new Word.Application
            {
                Visible = true
            };

            Document = Application.Documents.
                       Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);

            Word.Section section = Document.Sections.First;

            section.PageSetup.PageHeight = Constants.CreatorConstants.PageSize;
            section.PageSetup.PageWidth  = Constants.CreatorConstants.PageSize;
        }
예제 #6
0
        private void btn_WordList_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document    doc      = Globals.ThisAddIn.Application.ActiveDocument;
            HashSet <string> wordlist = new HashSet <string>();

            foreach (Word.Range rng in TextHelpers.GetText(doc))
            {
                string txt = rng.Text;

                //strip punctuation
                txt = TextHelpers.StripPunctuation(txt);

                //get word list
                HashSet <string> newwords = TextHelpers.ToWords(txt);
                wordlist.UnionWith(newwords);
            }

            //strip words that are all numbers
            wordlist = TextHelpers.RemoveNumbers(wordlist);

            //Create new document
            Word.Document  newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Word List\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "This is a proofreading tool. It takes every word in the document, strips the punctuation, removes words that consist only of numbers, and then presents them all in alphabetical order. This is a great way to find typos and inconsistencies.\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "Capitalization is retained as is. That means that words that appear at the beginning of a sentence will appear capitalized.\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(3);

            string[] words = wordlist.ToArray();
            Array.Sort(words);
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = string.Join("\n", words) + "\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
        }
예제 #7
0
        public void InsertShape(Word.Document doc)
        {
            try
            {
                Word.Section      sec = doc.Sections[1];
                Word.HeaderFooter foo = sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];

                Word.Range rng = foo.Range;

                float leftPos = doc.PageSetup.PageWidth - doc.PageSetup.RightMargin;
                float topPos  = doc.PageSetup.PageHeight - doc.PageSetup.BottomMargin;

                Word.Shape shp = doc.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                                                       leftPos, topPos, 50, 20, rng);

                shp.TextFrame.TextRange.Text = "Text";
                shp.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionBottomMarginArea;
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #8
0
        /// <summary>
        /// Creates a header graphic
        /// </summary>
        public override void CreateHeaderGraphic(string path = null)
        {
            try
            {
                // add header graphics
                // save the graphic before its path can be referenced
                if (!File.Exists(Global.appDataPath + "ACAS.jpg"))
                {
                    Image i = Resources.Resources.ACAS;
                    // recommended before save
                    Thread.Sleep(30);
                    i.Save(Global.appDataPath + "ACAS.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                // get the word document range of the header
                Word.Section firstSection       = document.Sections.First;
                Word.Range   headerSectionRange = firstSection.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;

                // get the shape back, put in the header and resize
                Word.InlineShape ACASLogo = headerSectionRange.InlineShapes.AddPicture(Global.appDataPath + "ACAS.jpg", false, true);

                // thread sleep to allow COM interop to catch up
                Thread.Sleep(100);

                // scale height and width
                ACASLogo.ScaleHeight = 55.0F;
                ACASLogo.ScaleWidth  = 55.0F;
            }
            catch (ExternalException e)
            {
                (new Logger())
                .SetLoggingType(Logger.Type.Warning)
                .SetMessage(e.Message + "Image could not be saved server side")
                .Display();
            }
        }
예제 #9
0
        /// <summary>
        /// Gets whether or not a specific header/footer type is visible in a given section.
        /// </summary>
        /// <param name="Section">The section to check.</param>
        /// <param name="HeaderFooterIndex">The header/footer to check for.</param>
        /// <returns>True if visible, otherwise False.</returns>
        internal static bool GetHeaderFooterVisibility(Word.Section Section, Word.WdHeaderFooterIndex HeaderFooterIndex)
        {
            Word.Range StartOfSection = Section.Range.Duplicate;
            Word.Range EndOfSection   = Section.Range.Duplicate;

            //set ranges
            StartOfSection.End = StartOfSection.Start;

            //get start/end page
            int StartingPageNumber = (int)StartOfSection.get_Information(Word.WdInformation.wdActiveEndAdjustedPageNumber);
            int EndingPageNumber   = (int)EndOfSection.get_Information(Word.WdInformation.wdActiveEndAdjustedPageNumber);

            //first page header in use?
            bool FirstPageVisible = (Section.PageSetup.DifferentFirstPageHeaderFooter == -1);

            if (FirstPageVisible && HeaderFooterIndex == Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage)
            {
                return(true);
            }

            //even page header in use?
            bool EvenPagesInUse = (Section.PageSetup.OddAndEvenPagesHeaderFooter == -1);

            if (!EvenPagesInUse && HeaderFooterIndex == Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages)
            {
                return(false);
            }

            if (EndingPageNumber - StartingPageNumber >= 2)
            {
                //if there are more than three pages, then the type is definitely showing
                return(true);
            }
            else if (EndingPageNumber - StartingPageNumber == 1)
            {
                //if there are two pages, need to check
                switch (HeaderFooterIndex)
                {
                case Word.WdHeaderFooterIndex.wdHeaderFooterPrimary:
                    if (!EvenPagesInUse || !FirstPageVisible)
                    {
                        return(true);
                    }
                    else
                    {
                        return((StartingPageNumber + 1) % 2 != 0);      // is next page odd
                    }

                case Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages:
                    if (!FirstPageVisible)
                    {
                        return(true);
                    }
                    else
                    {
                        return((StartingPageNumber + 1) % 2 == 0);      // is next page even
                    }
                }
            }

            // == 1
            switch (HeaderFooterIndex)
            {
            case Word.WdHeaderFooterIndex.wdHeaderFooterPrimary:
                if (FirstPageVisible)     // first page is showing
                {
                    return(false);
                }
                else if (EvenPagesInUse)     // first page not showing and even showing
                {
                    return(StartingPageNumber % 2 != 0);
                }
                else              //first page not showing, even not showing
                {
                    return(true); // is page odd
                }

            case Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages:
                if (FirstPageVisible)     // first page is showing
                {
                    return(false);
                }
                else if (EvenPagesInUse)     // first page not showing and even showing
                {
                    return(StartingPageNumber % 2 == 0);
                }
                else               //first page not showing, even not showing
                {
                    return(false); // is page odd
                }
            }

            Debug.Fail("should never fall through on visibility");
            return(false);
        }
예제 #10
0
        private void InsertTitleBK(MSWord.Document doc, MSWord.Application app)
        {
            int    bknum = 6;
            string bknum_string;

            mydoc.Bookmarks.DefaultSorting = 0;
            mydoc.Bookmarks.ShowHidden     = false;
            MSWord.Section mysec  = mydoc.Sections.Add();
            object         unit   = MSWord.WdUnits.wdLine;
            object         count  = 1;
            object         extend = MSWord.WdMovementType.wdMove;

            MSWord.Range  r    = mysec.Range;
            object        rng  = (object)r;
            SqlConnection conn = new SqlConnection();
            SqlCommand    com  = DatabaseClass.ConnectionToCommad(conn, conStr);

            com.CommandText = "select TitleNum from TitleTable where DocID=@DocID order by TitleNum";
            com.Parameters.Clear();
            com.Parameters.AddWithValue("DocID", IsEditing.DOCID);
            SqlDataReader dr = com.ExecuteReader();

            while (dr.Read())
            {
                //word书签不支持符合“|”,因此在这里需要转换,使用字符“l”
                bknum_string = bknum.ToString();
                if (bknum_string.Length == 1)
                {
                    bknum_string = "00" + bknum_string;
                }
                else if (bknum_string.Length == 2)
                {
                    bknum_string = "0" + bknum_string;
                }
                string   titlenum = dr[0].ToString();
                string[] title    = titlenum.Split('|');
                titlenum = String.Join("l", title);
                string bkmark = "bk" + bknum_string + "_" + titlenum;
                mydoc.Bookmarks.Add(bkmark, ref rng);
                r = GetBKRange(mydoc, bkmark);
                r.Select();
                r.InsertAfter("\n");
                msapp.Selection.MoveDown(ref unit, ref count, ref extend);
                r      = msapp.Selection.Range;
                rng    = (object)r;
                bknum += 1;
            }
            DisposeClose.Disposeclose(dr);
            DisposeClose.Disposeclose(com);
            DisposeClose.Disposeclose(conn);
            //最后插入参考文献

            bknum_string = bknum.ToString();
            if (bknum_string.Length == 1)
            {
                bknum_string = "00" + bknum_string;
            }
            else if (bknum_string.Length == 2)
            {
                bknum_string = "0" + bknum_string;
            }

            string bk_bibliography = "bk" + bknum_string + "_bibliography";

            mydoc.Bookmarks.Add(bk_bibliography, ref rng);
            r = GetBKRange(mydoc, bk_bibliography);
            r.Select();
            r.InsertAfter("\n");
            msapp.Selection.MoveDown(ref unit, ref count, ref extend);
            r            = msapp.Selection.Range;
            rng          = (object)r;
            bknum       += 1;
            bknum_string = bknum.ToString();
            if (bknum_string.Length == 1)
            {
                bknum_string = "00" + bknum_string;
            }
            else if (bknum_string.Length == 2)
            {
                bknum_string = "0" + bknum_string;
            }
            string bk_bcontent = "bk" + bknum_string + "_bcontent";

            mydoc.Bookmarks.Add(bk_bcontent, ref rng);
        }
예제 #11
0
        private void btn_PhraseFrequency_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            uint          newminlen;
            uint          newmaxlen;

            UInt32.TryParse(edit_MinPhraseLen.Text, out newminlen);
            UInt32.TryParse(edit_MaxPhraseLen.Text, out newmaxlen);
            if ((newminlen != 0) && (newmaxlen != 0) && (newminlen <= newmaxlen))
            {
                Properties.Settings.Default.minphraselen = newminlen;
                Properties.Settings.Default.maxphraselen = newmaxlen;
                Properties.Settings.Default.Save();

                Dictionary <string, uint> phrases = new Dictionary <string, uint>();
                //Iterate through all text
                foreach (Word.Range rng in TextHelpers.GetText(doc))
                {
                    //Break into sentences
                    foreach (Word.Range sentence in rng.Sentences)
                    {
                        //Strip punctuation
                        string nopunc = TextHelpers.StripPunctuation(sentence.Text);
                        nopunc = nopunc.Replace("  ", " ");
                        //Break into words
                        string[] words = nopunc.Split(' ');
                        //Extract phrases
                        for (uint i = newminlen; i <= newmaxlen; i++)
                        {
                            for (int start = 0; start < words.Length - i; start++)
                            {
                                List <string> phraselst = new List <string>();
                                for (int idx = 0; idx < i; idx++)
                                {
                                    phraselst.Add(words[start + idx]);
                                }
                                string phrase = string.Join(" ", phraselst).ToLower();
                                //Add to data structre
                                if (phrases.ContainsKey(phrase))
                                {
                                    phrases[phrase]++;
                                }
                                else
                                {
                                    phrases[phrase] = 1;
                                }
                            }
                        }
                    }
                }

                //Display results

                //Create new document
                Word.Document  newdoc = Globals.ThisAddIn.Application.Documents.Add();
                Word.Paragraph pgraph;

                //Intro text
                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.set_Style(newdoc.Styles["Heading 1"]);
                pgraph.Range.Text = "Phrase Frequency List\n";
                pgraph            = newdoc.Content.Paragraphs.Add();
                pgraph.set_Style(newdoc.Styles["Normal"]);
                pgraph.Range.Text = "Punctuation (other than apostrophes) has been removed. All words have been lowercased for comparison.\n";

                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
                Word.Section sec = newdoc.Sections[2];
                sec.PageSetup.TextColumns.SetCount(2);

                var phraselist = phrases.Where(x => x.Value > 1).ToList();
                phraselist.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
                foreach (var pair in phraselist)
                {
                    pgraph = newdoc.Content.Paragraphs.Add();
                    pgraph.set_Style(newdoc.Styles["Normal"]);
                    pgraph.Range.Text = pair.Key + "\t" + pair.Value.ToString() + "\n";
                }

                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
                newdoc.GrammarChecked = true;
            }
            else
            {
                MessageBox.Show("The phrase length fields must contain numbers greater than zero, and the minimum length must be less than or equal to the maximum length.");
            }
        }
예제 #12
0
        private void btn_WordFreq_Click(object sender, RibbonControlEventArgs e)
        {
            ProgressDialog d = new ProgressDialog();

            d.Show();

            Stopwatch watch = new Stopwatch();

            watch.Start();
            Word.Document             doc      = Globals.ThisAddIn.Application.ActiveDocument;
            Dictionary <string, uint> wordlist = new Dictionary <string, uint>();
            Regex re_allnums = new Regex(@"^\d+$");

            IEnumerable <Word.Range> textranges = TextHelpers.GetText(doc);

            d.pbMax = textranges.Count();
            d.pbVal = 0;
            foreach (Word.Range rng in textranges)
            {
                d.pbVal++;
                string txt = rng.Text;

                //strip punctuation
                txt = TextHelpers.StripPunctuation(txt);


                string[] substrs = Regex.Split(txt, @"\s+");
                foreach (string word in substrs)
                {
                    Match m = re_allnums.Match(word);
                    if (!m.Success)
                    {
                        if (word.Trim() != "")
                        {
                            if (wordlist.ContainsKey(word))
                            {
                                wordlist[word]++;
                            }
                            else
                            {
                                wordlist.Add(word, 1);
                            }
                        }
                    }
                }
            }
            Debug.WriteLine("Counts tabulated. Time elapsed: " + watch.Elapsed.ToString());
            watch.Restart();

            //Create new document
            Word.Document  newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Word Frequency List\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "Capitalization is retained as is. That means that words that appear at the beginning of a sentence will appear capitalized. Don't forget that you can sort the table!\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "Total words found (case sensitive): " + wordlist.Count.ToString() + "\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(3);

            var words = wordlist.ToList();

            words.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
            newdoc.Tables.Add(pgraph.Range, words.Count, 2);
            //newdoc.Tables.Add(pgraph.Range, 1, 2);
            newdoc.Tables[1].AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
            newdoc.Tables[1].AllowAutoFit = true;
            d.pbMax = words.Count;
            d.pbVal = 0;
            int row = 1;

            foreach (var pair in words)
            {
                d.pbVal++;
                //newdoc.Tables[1].Rows.Add();
                Word.Cell cell = newdoc.Tables[1].Cell(row, 1);
                cell.Range.Text = pair.Key;
                cell            = newdoc.Tables[1].Cell(row, 2);
                cell.Range.Text = pair.Value.ToString();
                row++;
            }

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
            Debug.WriteLine("All done. Time elapsed: " + watch.Elapsed.ToString());
            watch.Stop();
            d.Hide();
        }
예제 #13
0
        private void btn_ProperNouns_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Document    doc      = Globals.ThisAddIn.Application.ActiveDocument;
            HashSet <string> wordlist = new HashSet <string>();

            foreach (Word.Range rng in TextHelpers.GetText(doc))
            {
                string     txt   = rng.Text;
                Word.Style style = rng.get_Style();
                if (style != null)
                {
                    Regex re_heading = new Regex(@"(?i)(heading|title|date|toc)");
                    Match m          = re_heading.Match(style.NameLocal);
                    if (m.Success)
                    {
                        continue;
                    }
                }

                HashSet <string> propers = new HashSet <string>();
                propers = TextHelpers.ProperNouns(txt);
                wordlist.UnionWith(propers);
            }

            //Produce the groupings
            HashSet <string> capped = TextHelpers.KeepCaps(wordlist);

            //DoubleMetaphone
            Dictionary <ushort, List <string> > mpgroups = new Dictionary <ushort, List <string> >();
            //Dictionary<string, List<string>> mpgroups = new Dictionary<string, List<string>>();
            ShortDoubleMetaphone sdm = new ShortDoubleMetaphone();

            //HashSet<string> tested = new HashSet<string>();

            foreach (string word in capped)
            {
                /*
                 * if (tested.Contains(word))
                 * {
                 *  continue;
                 * }
                 * else
                 * {
                 *  tested.Add(word);
                 * }
                 */
                sdm.computeKeys(word);
                ushort pri = sdm.PrimaryShortKey;
                ushort alt = sdm.AlternateShortKey;
                if (mpgroups.ContainsKey(pri))
                {
                    mpgroups[pri].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[pri] = node;
                }
                if (mpgroups.ContainsKey(alt))
                {
                    mpgroups[alt].Add(word);
                }
                else
                {
                    List <string> node = new List <string>();
                    node.Add(word);
                    mpgroups[alt] = node;
                }
            }

            //Edit Distance
            List <string> dtested = new List <string>();
            int           mindist;

            int.TryParse(Properties.Settings.Default.mindist, out mindist);
            if (mindist == 0)
            {
                mindist = 2;
            }
            Dictionary <string, List <string> > distgroups = new Dictionary <string, List <string> >();

            foreach (string word1 in capped)
            {
                if (dtested.Contains(word1))
                {
                    continue;
                }
                else
                {
                    dtested.Add(word1);
                }

                if (word1.Length <= mindist)
                {
                    continue;
                }

                foreach (string word2 in capped)
                {
                    if (word2.Length <= mindist)
                    {
                        continue;
                    }
                    int dist = TextHelpers.EditDistance(word1, word2);
                    //int percent = (int)Math.Round((dist / word1.Length) * 100.0);
                    if ((dist > 0) && (dist <= mindist))
                    //if ((dist > 0) && (percent <= distpercent))
                    {
                        dtested.Add(word2);
                        if (distgroups.ContainsKey(word1))
                        {
                            distgroups[word1].Add(word2);
                        }
                        else
                        {
                            List <string> node = new List <string>();
                            node.Add(word2);
                            distgroups[word1] = node;
                        }
                    }
                }
            }

            //Create new document
            Word.Document newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.View     view   = Globals.ThisAddIn.Application.ActiveWindow.View;
            view.DisplayPageBoundaries = false;
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Proper Noun Checker\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "This tool only looks at words that start with a capital letter. It then uses phonetic comparison and edit distance to find other proper nouns that are similar. Words in all caps (acronyms) are not included.\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "The system tries to ignore words at the beginning of sentences and in headers. This means some errors may go unseen, so use multiple tools!\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.Range.Text = "Most of what you see here are false positives! That's unavoidable. But it still catches certain otherwise-hard-to-find misspellings.\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(2);
            sec.PageSetup.TextColumns.LineBetween = -1;

            //Distance
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Edit Distance (" + mindist + ")\n";

            foreach (string key in distgroups.Keys)
            {
                List <string> group = distgroups[key];
                pgraph = newdoc.Content.Paragraphs.Add();
                pgraph.set_Style(newdoc.Styles["Normal"]);
                pgraph.Range.Text = key + ", " + string.Join(", ", group) + "\n";
            }

            pgraph.Range.InsertBreak(Word.WdBreakType.wdPageBreak);
            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            //Word.InlineShape line = pgraph.Range.InlineShapes.AddHorizontalLineStandard();
            //line.Height = 2;
            //line.Fill.Solid();
            //line.HorizontalLineFormat.NoShade = true;
            //line.Fill.ForeColor.RGB = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
            //line.HorizontalLineFormat.PercentWidth = 90;
            //line.HorizontalLineFormat.Alignment = WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;
            //sec = newdoc.Sections[3];
            //sec.PageSetup.TextColumns.SetCount(2);
            //sec.PageSetup.TextColumns.LineBetween = -1;

            //Metaphone
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 2"]);
            //pgraph.KeepWithNext = 0;
            pgraph.Range.Text = "Phonetic Comparisons\n";

            foreach (ushort key in mpgroups.Keys)
            {
                if (key == 65535)
                {
                    continue;
                }
                List <string> group = mpgroups[key];
                if (group.Count > 1)
                {
                    pgraph = newdoc.Content.Paragraphs.Add();
                    pgraph.set_Style(newdoc.Styles["Normal"]);
                    pgraph.Range.Text = string.Join(", ", group) + "\n";
                }
            }

            //pgraph = newdoc.Content.Paragraphs.Add();
            //pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
        }
예제 #14
0
        private void btnKreiraj_Click(object sender, EventArgs e)
        {
            Object oMissing = System.Reflection.Missing.Value;

            Object oTemplatePath;// = "D:\\MyTemplate.dotx";
            string oTempName;

            try
            {
                var templejt = context.tblTemplejts.Single <tblTemplejt>(ee => ee.ImeTemp == cmbTemp.Text);
                indexTemp = templejt.IDTemplejt;

                var klient = context.tblKlientis.Single <tblKlienti>(ee => ee.ImeFirma == cmbKlient.Text);
                indexKlient = klient.IDFirma;

                oTempName     = templejt.ImeTemp;
                oTemplatePath = templejt.LokacijaTemplejt + '/' + oTempName + ".dotx";
            }
            catch (Exception)
            {
                MessageBox.Show("Нема доволно аргументи за креирање на понуда!", "Недоволно аргументи", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var Vraboten = context.Vrabotens.Single <Vraboten>(ee => ee.VrabotenID == vrabotenID);
            var Klient   = context.tblKlientis.Single <tblKlienti>(ee => ee.ImeFirma == cmbKlient.Text);

            wordApp = new Microsoft.Office.Interop.Word.Application();
            wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);


            // context ********
            foreach (Field myMergeField in wordDoc.Fields)
            {
                Range  rngFieldCode = myMergeField.Code;
                String fieldText    = rngFieldCode.Text;

                // ONLY GETTING THE MAILMERGE FIELDS

                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    // THE TEXT COMES IN THE FORMAT OF
                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

                    int endMerge = fieldText.IndexOf("\\");

                    int fieldNameLength = fieldText.Length - endMerge;

                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//

                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

                    switch (fieldName)
                    {
                    case "korisnik":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.ImeFirma);
                        break;
                    }

                    case "mesto":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.Grad);
                        break;
                    }

                    case "adresa":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.Adresa);
                        break;
                    }

                    case "vaznost":
                    {
                        int mesec = int.Parse(dtVaznost.Value.Month.ToString());
                        myMergeField.Select();
                        wordApp.Selection.TypeText(dtVaznost.Value.Day.ToString() + " " + najdiMesec(mesec) + " " + dtVaznost.Value.Year.ToString());
                        break;
                    }

                    case "izdadenoNa":
                    {
                        int mesec = int.Parse(DateTime.Now.Month.ToString());
                        myMergeField.Select();
                        wordApp.Selection.TypeText(DateTime.Now.Day.ToString() + " " + najdiMesec(mesec) + " " + DateTime.Now.Year.ToString());
                        break;
                    }

                    case "vrabIme":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Vraboten.ImeV);
                        break;
                    }

                    case "vrabPrezime":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Vraboten.PrezimeV);
                        break;
                    }

                    case "stavka":
                    {
                        myMergeField.Select();
                        //   wordApp.Selection.TypeText("");
                        Microsoft.Office.Interop.Word.Selection wrdSelect = wordApp.Selection;
                        Microsoft.Office.Interop.Word.Table     wrdTable  = wordDoc.Tables.Add(wrdSelect.Range, 1, 6, ref oMissing, ref oMissing);

                        wrdTable.Range.ParagraphFormat.RightIndent = wordDoc.Paragraphs.RightIndent;
                        wrdTable.Borders.OutsideLineStyle          = WdLineStyle.wdLineStyleSingle;
                        wrdTable.Borders.OutsideLineWidth          = WdLineWidth.wdLineWidth075pt;
                        wrdTable.Borders.InsideLineStyle           = WdLineStyle.wdLineStyleSingle;
                        wrdTable.Borders.InsideLineWidth           = WdLineWidth.wdLineWidth075pt;

                        wrdTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                        wrdTable.Columns[1].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[2].SetWidth(150, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[3].SetWidth(60, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[4].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[5].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[6].SetWidth(50, WdRulerStyle.wdAdjustNone);

                        wrdTable.Cell(1, 1).Range.Text = "Шифра";
                        wrdTable.Cell(1, 2).Range.Text = "Назив";
                        wrdTable.Cell(1, 3).Range.Text = "Количина";
                        wrdTable.Cell(1, 4).Range.Text = "Ед. Мерка";
                        wrdTable.Cell(1, 5).Range.Text = "Цена";
                        wrdTable.Cell(1, 6).Range.Text = "Износ";
                        // wrdTable.Cell(0, 0).Range.SetRange(0,50);

                        for (int i = 0; i < grdStavka.RowCount; i++)
                        {
                            wordDoc.Tables[1].Rows.Add(ref oMissing);
                            wrdTable.Cell(i + 2, 1).Range.Text = grdStavka[0, i].Value.ToString();
                            wrdTable.Cell(i + 2, 2).Range.Text = grdStavka[1, i].Value.ToString();
                            wrdTable.Cell(i + 2, 3).Range.Text = grdStavka[2, i].Value.ToString();
                            wrdTable.Cell(i + 2, 4).Range.Text = grdStavka[3, i].Value.ToString();
                            wrdTable.Cell(i + 2, 5).Range.Text = grdStavka[4, i].Value.ToString();
                            wrdTable.Cell(i + 2, 6).Range.Text = grdStavka[5, i].Value.ToString();
                        }

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 5));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "Износ";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtVkupno.Text.ToString();

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        //    wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 4));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "ДДВ 18%";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtDDV.Text.ToString();

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        //   wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 4));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "Вкупно за плаќање";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtIznos_DDV.Text.ToString();
                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }
                }
            }

            var addArhivski = new tblArhiva();

            context.tblArhivas.InsertOnSubmit(addArhivski);
            context.SubmitChanges();
            //   context = new BrziPonudiDataContext();
            var posledenArhivski = addArhivski.IDArhivskiBroj;
            //   int idArhivski = addArhivski.IDArhivskiBroj;
            //imame indextemp od prethodno;
            int    godina     = DateTime.Now.Year;
            string arhivskiBR = posledenArhivski.ToString() + "-" + indexTemp + "-" + godina.ToString();

            addArhivski.Arhivskibroj = arhivskiBR;
            var dokument = new tblDokumenti()
            {
                Arhivskibroj      = arhivskiBR,
                IDFirma           = indexKlient,
                IDVraboteni       = vrabotenID,
                DataZaOdgovor     = dtVaznost.Value.Date,
                KalendarskaGodina = godina.ToString(),
                IzdadenoNa        = DateTime.Now,
                IDTemp            = indexTemp,
            };

            context.tblDokumentis.InsertOnSubmit(dokument);
            context.SubmitChanges();


            //    context = new BrziPonudiDataContext();
            //    dokument = context.tblDokumentis.LastOrDefault();
            var posledenDokument = dokument.IDDokument;

            for (int stavkaProizvodi = 0; stavkaProizvodi < grdStavka.RowCount; stavkaProizvodi++)
            {
                var stavka = new tblStavka()
                {
                    IDProizvodPonuda = int.Parse(grdStavka[0, stavkaProizvodi].Value.ToString()),
                    Kolicina         = grdStavka[2, stavkaProizvodi].Value.ToString(),
                    Cena             = grdStavka[4, stavkaProizvodi].Value.ToString(),
                    IDPonuda         = posledenDokument,
                };
                context.tblStavkas.InsertOnSubmit(stavka);
            }
            context.SubmitChanges();
            // header and footer **********
            bool header = true;

label1:

            Microsoft.Office.Interop.Word.Section sec = wordDoc.Sections[1];
            Microsoft.Office.Interop.Word.Range rng = sec.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            if (!header)
            {
                rng = sec.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            }

            foreach (Microsoft.Office.Interop.Word.Field fld in rng.Fields)
            {
                Range  rngFieldCode = fld.Code;
                String fieldText    = rngFieldCode.Text;
                // if (fld.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField)
                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    int endMerge = fieldText.IndexOf("\\");

                    int fieldNameLength = fieldText.Length - endMerge;

                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();

                    //   String dataFieldName = fld.Code.Text.Trim();
                    if (fieldName == "IDTemp")
                    {
                        fld.Select();
                        wordApp.Selection.TypeText(indexTemp.ToString());
                    }

                    if (fieldName == "arhiva")
                    {
                        fld.Select();
                        wordApp.Selection.TypeText(arhivskiBR);
                    }
                }
            }
            if (!header)
            {
                goto label2;
            }
            else
            {
                header = false;
                goto label1;
            }
label2:
            wordDoc.SaveAs(@oTemplatePath + ".docx");
            wordApp.Documents.Open(@oTemplatePath + ".docx");
            wordDoc.PrintPreview();
        }
예제 #15
0
        void prigotviZaPecatenje(int key)
        {
            var dok      = context.tblDokumentis.Single <tblDokumenti>(ee => ee.IDDokument == key);
            var Klient   = context.tblKlientis.Single <tblKlienti>(ee => ee.IDFirma == dok.IDFirma);
            var Vraboten = context.Vrabotens.Single <Vraboten>(ee => ee.VrabotenID == dok.IDVraboteni);
            var templejt = context.tblTemplejts.Single <tblTemplejt>(ee => ee.IDTemplejt == dok.IDTemp);


            Microsoft.Office.Interop.Word.Application wordApp;
            Document wordDoc = new Document();

            Object oMissing = System.Reflection.Missing.Value;

            Object oTemplatePath;// = "D:\\MyTemplate.dotx";
            string oTempName;

            oTempName     = templejt.ImeTemp;
            oTemplatePath = templejt.LokacijaTemplejt + '/' + oTempName + ".dotx";


            wordApp = new Microsoft.Office.Interop.Word.Application();
            wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);



            // context ********
            foreach (Field myMergeField in wordDoc.Fields)
            {
                Range  rngFieldCode = myMergeField.Code;
                String fieldText    = rngFieldCode.Text;

                // ONLY GETTING THE MAILMERGE FIELDS

                if (fieldText.StartsWith(" MERGEFIELD"))
                {
                    // THE TEXT COMES IN THE FORMAT OF
                    // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
                    // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"

                    int endMerge = fieldText.IndexOf("\\");

                    int fieldNameLength = fieldText.Length - endMerge;

                    String fieldName = fieldText.Substring(11, endMerge - 11);

                    // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                    fieldName = fieldName.Trim();

                    // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//

                    // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE

                    switch (fieldName)
                    {
                    case "korisnik":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.ImeFirma);
                        break;
                    }

                    case "mesto":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.Grad);
                        break;
                    }

                    case "adresa":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Klient.Adresa);
                        break;
                    }

                    case "vaznost":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(dok.DataZaOdgovor.ToString());
                        break;
                    }

                    case "izdadenoNa":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(dok.IzdadenoNa.ToString());
                        break;
                    }

                    case "vrabIme":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Vraboten.ImeV);
                        break;
                    }

                    case "vrabPrezime":
                    {
                        myMergeField.Select();
                        wordApp.Selection.TypeText(Vraboten.PrezimeV);
                        break;
                    }

                    case "stavka":
                    {
                        myMergeField.Select();
                        //   wordApp.Selection.TypeText("");
                        Microsoft.Office.Interop.Word.Selection wrdSelect = wordApp.Selection;
                        Microsoft.Office.Interop.Word.Table     wrdTable  = wordDoc.Tables.Add(wrdSelect.Range, 1, 6, ref oMissing, ref oMissing);

                        wrdTable.Range.ParagraphFormat.RightIndent = wordDoc.Paragraphs.RightIndent;
                        wrdTable.Borders.OutsideLineStyle          = WdLineStyle.wdLineStyleSingle;
                        wrdTable.Borders.OutsideLineWidth          = WdLineWidth.wdLineWidth075pt;
                        wrdTable.Borders.InsideLineStyle           = WdLineStyle.wdLineStyleSingle;
                        wrdTable.Borders.InsideLineWidth           = WdLineWidth.wdLineWidth075pt;

                        wrdTable.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                        wrdTable.Columns[1].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[2].SetWidth(150, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[3].SetWidth(60, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[4].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[5].SetWidth(50, WdRulerStyle.wdAdjustNone);
                        wrdTable.Columns[6].SetWidth(50, WdRulerStyle.wdAdjustNone);

                        wrdTable.Cell(1, 1).Range.Text = "Шифра";
                        wrdTable.Cell(1, 2).Range.Text = "Назив";
                        wrdTable.Cell(1, 3).Range.Text = "Количина";
                        wrdTable.Cell(1, 4).Range.Text = "Ед. Мерка";
                        wrdTable.Cell(1, 5).Range.Text = "Цена";
                        wrdTable.Cell(1, 6).Range.Text = "Износ";
                        // wrdTable.Cell(0, 0).Range.SetRange(0,50);

                        for (int i = 0; i < grdStavka.RowCount - 1; i++)
                        {
                            wordDoc.Tables[1].Rows.Add(ref oMissing);
                            wrdTable.Cell(i + 2, 1).Range.Text = grdStavka[0, i].Value.ToString();
                            wrdTable.Cell(i + 2, 2).Range.Text = grdStavka[1, i].Value.ToString();
                            wrdTable.Cell(i + 2, 3).Range.Text = grdStavka[2, i].Value.ToString();
                            wrdTable.Cell(i + 2, 4).Range.Text = grdStavka[3, i].Value.ToString();
                            wrdTable.Cell(i + 2, 5).Range.Text = grdStavka[4, i].Value.ToString();
                            wrdTable.Cell(i + 2, 6).Range.Text = grdStavka[5, i].Value.ToString();
                        }

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 5));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "Износ";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtVkupno.Text.ToString();

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        //    wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 4));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "ДДВ 18%";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtDDV.Text.ToString();

                        wordDoc.Tables[1].Rows.Add(ref oMissing);
                        //   wrdTable.Cell(wrdTable.Rows.Count, 1).Merge(wrdTable.Cell(wrdTable.Rows.Count, 4));
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.Text = "Вкупно за плаќање";
                        wrdTable.Cell(wrdTable.Rows.Count, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                        wrdTable.Cell(wrdTable.Rows.Count, 2).Range.Text = txtIznos_DDV.Text.ToString();
                        break;
                    }

                    default:
                    {
                        break;
                    }
                    }

                    // header and footer **********
                    bool header = true;
label1:

                    Microsoft.Office.Interop.Word.Section sec = wordDoc.Sections[1];
                    Microsoft.Office.Interop.Word.Range rng = sec.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    if (!header)
                    {
                        rng = sec.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    }

                    foreach (Microsoft.Office.Interop.Word.Field fld in rng.Fields)
                    {
                        rngFieldCode = fld.Code;
                        fieldText    = rngFieldCode.Text;
                        // if (fld.Type == Microsoft.Office.Interop.Word.WdFieldType.wdFieldMergeField)
                        if (fieldText.StartsWith(" MERGEFIELD"))
                        {
                            endMerge = fieldText.IndexOf("\\");

                            fieldNameLength = fieldText.Length - endMerge;

                            fieldName = fieldText.Substring(11, endMerge - 11);

                            // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE

                            fieldName = fieldName.Trim();

                            //   String dataFieldName = fld.Code.Text.Trim();
                            if (fieldName == "IDTemp")
                            {
                                fld.Select();
                                wordApp.Selection.TypeText(dok.IDTemp.ToString());
                            }

                            if (fieldName == "arhiva")
                            {
                                fld.Select();
                                wordApp.Selection.TypeText(dok.Arhivskibroj.ToString());
                            }
                        }
                    }
                    if (!header)
                    {
                        goto label2;
                    }
                    else
                    {
                        header = false;
                        goto label1;
                    }
label2:
                    wordDoc.SaveAs(@oTemplatePath + ".docx");
                    wordApp.Documents.Open(@oTemplatePath + ".docx");
                    wordDoc.PrintPreview();
                }
            }
        }
예제 #16
0
        public void WordFrequencyList()
        {
            //ProgressDialog d = new ProgressDialog();
            //d.Show();

            Stopwatch watch = new Stopwatch();

            watch.Start();

            Dictionary <string, uint> wordlist = new Dictionary <string, uint>();

            wordlist = GetWordFrequencyList();

            //Debug.WriteLine("Counts tabulated. Time elapsed: " + watch.Elapsed.ToString());
            watch.Restart();

            //Create new document
            Word.Document  newdoc = Globals.ThisAddIn.Application.Documents.Add();
            Word.Paragraph pgraph;

            //Intro text
            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Heading 1"]);
            pgraph.Range.Text = "Word Frequency List\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "Capitalization is retained as is. That means that words that appear at the beginning of a sentence will appear capitalized. Don't forget that you can sort the table!\n";
            pgraph            = newdoc.Content.Paragraphs.Add();
            pgraph.set_Style(newdoc.Styles["Normal"]);
            pgraph.Range.Text = "Total words found (case sensitive): " + wordlist.Count.ToString() + "\n";

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            Word.Section sec = newdoc.Sections[2];
            sec.PageSetup.TextColumns.SetCount(3);

            var words = wordlist.ToList();

            words.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
            newdoc.Tables.Add(pgraph.Range, words.Count, 2);
            //newdoc.Tables.Add(pgraph.Range, 1, 2);
            newdoc.Tables[1].AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
            newdoc.Tables[1].AllowAutoFit = true;
            //d.pbMax = words.Count;
            //d.pbVal = 0;
            int row = 1;

            foreach (var pair in words)
            {
                //d.pbVal++;
                //newdoc.Tables[1].Rows.Add();
                Word.Cell cell = newdoc.Tables[1].Cell(row, 1);
                cell.Range.Text = pair.Key;
                cell            = newdoc.Tables[1].Cell(row, 2);
                cell.Range.Text = pair.Value.ToString();
                row++;
            }

            pgraph = newdoc.Content.Paragraphs.Add();
            pgraph.Range.InsertBreak(Word.WdBreakType.wdSectionBreakContinuous);
            newdoc.GrammarChecked = true;
            //Debug.WriteLine("All done. Time elapsed: " + watch.Elapsed.ToString());
            watch.Stop();
            //d.Hide();
        }