Ejemplo n.º 1
0
        public CounterData getCounters(String filePath)
        {
            CounterData counters = new CounterData {
                wordCount = 0, charCount = 0, paraCount = 0, pageCount = 0
            };
            string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);

            log.Info("Counting " + fileName);
            Microsoft.Office.Interop.Word.Application word = null;
            Microsoft.Office.Interop.Word.Document    doc  = null;

            object missing     = Type.Missing;
            object saveChanges = false;
            object includeFootnotesAndEndnotes = true;

            Microsoft.Office.Interop.Word.WdStatistic wordStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticWords;
            Microsoft.Office.Interop.Word.WdStatistic charStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticCharacters;
            Microsoft.Office.Interop.Word.WdStatistic paraStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticParagraphs;
            Microsoft.Office.Interop.Word.WdStatistic pageStats = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;

            try
            {
                word = new Microsoft.Office.Interop.Word.Application();
                doc  = new Microsoft.Office.Interop.Word.Document();
                object objFilePath = @filePath;

                /*
                 * Document OpenNoRepairDialog(ref Object FileName,
                 *          ref Object ConfirmConversions, ref Object ReadOnly, ref Object AddToRecentFiles, ref Object PasswordDocument,
                 *      ref Object PasswordTemplate, ref Object Revert, ref Object WritePasswordDocument, ref Object WritePasswordTemplate,
                 *          ref Object Format, ref Object Encoding, ref Object Visible, ref Object OpenAndRepair,
                 *          ref Object DocumentDirection, ref Object NoEncodingDialog, ref Object XMLTransform
                 *  )
                 */
                doc = word.Documents.OpenNoRepairDialog(ref objFilePath,
                                                        ref missing, true, 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);
                if (doc != null)
                {
                    doc.Activate();

                    counters.wordCount = doc.ComputeStatistics(wordStats, ref includeFootnotesAndEndnotes);
                    counters.charCount = doc.ComputeStatistics(charStats, ref includeFootnotesAndEndnotes);
                    counters.paraCount = doc.ComputeStatistics(paraStats, ref includeFootnotesAndEndnotes);
                    counters.pageCount = doc.ComputeStatistics(pageStats, ref includeFootnotesAndEndnotes);
                    log.Info(counters);
                }
                //doc.Save();
                word.Quit(ref saveChanges, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                word.Quit(ref saveChanges, ref missing, ref missing);
                log.Error(ex);
            }

            return(counters);
        }
Ejemplo n.º 2
0
        public int getpage(object file)
        {
            try
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                object nullobj = System.Reflection.Missing.Value;

                Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(
                    ref file, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj);
                doc.ActiveWindow.Selection.WholeStory();
                doc.ActiveWindow.Selection.Copy();
                IDataObject data = Clipboard.GetDataObject();

                // get number of pages
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int pages = doc.ComputeStatistics(stat, Type.Missing);

                //string text = data.GetData(DataFormats.Text).ToString();  //获取具体内容,此项目不需要

                doc.Close(ref nullobj, ref nullobj, ref nullobj);
                app.Quit(ref nullobj, ref nullobj, ref nullobj);


                return(pages);
            }
            catch (Exception ex)
            {
                ex.ToString();
                return(0);
            }
        }
Ejemplo n.º 3
0
        private static void ComputeStatistics()
        {
            int pagecount = 0;
            int wordcount = 0;

            object fileName  = Filename;
            object readOnly  = false;
            object isVisible = false;
            object objDNS    = Word.WdSaveOptions.wdPromptToSaveChanges;
            object missing   = System.Reflection.Missing.Value;

            Word._Application WordApp = new Word.ApplicationClass();

            Word._Document aDoc = null;

            try
            {
                aDoc = WordApp.Documents.Open
                       (
                    ref fileName, ref missing, ref readOnly,
                    ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref isVisible,
                    ref missing, ref missing, ref missing,
                    ref missing
                       );

                Word.WdStatistic pagestat = Word.WdStatistic.wdStatisticPages;
                Word.WdStatistic wordstat = Word.WdStatistic.wdStatisticWords;

                pagecount = aDoc.ComputeStatistics(pagestat, ref missing);
                wordcount = aDoc.ComputeStatistics(wordstat, ref missing);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (aDoc != null)
                {
                    aDoc.Close(ref objDNS, ref missing, ref missing);
                    Marshal.ReleaseComObject(aDoc);
                    aDoc = null;
                }
                if (WordApp != null)
                {
                    WordApp.Quit(ref objDNS, ref missing, ref missing);
                    Marshal.ReleaseComObject(WordApp);
                    WordApp = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            TotalPages = pagecount;
            NoOfWords  = wordcount;
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            Word.Application _app     = null;
            Word.Document    document = null;
            object           missing  = System.Reflection.Missing.Value;

            _app = new Word.Application();
            string wordFilePath = @"D:\work\53002\20160823\131163876229304835\6\2062\20160822003\中共陕西省委党校2016年论文\2013210084-陈伟丽.doc";

            document = _app.Documents.Open(wordFilePath, false, false, false, ref missing, missing, false, missing, missing, missing, missing, false, false, missing, true, missing);
            object What  = Word.WdGoToItem.wdGoToSection;
            object Which = Word.WdGoToDirection.wdGoToNext;

            Word.WdStatistic staticword = Word.WdStatistic.wdStatisticPages;
            int ipagecount = document.ComputeStatistics(staticword);//获得word文档的页数

            //跳转到指定的页数
            object pWhat  = Word.WdGoToItem.wdGoToPage;
            object pWhich = Word.WdGoToDirection.wdGoToAbsolute;

            Word.Document P_document = _app.Documents.Add(ref missing, ref missing, ref missing);
            for (int i = 1; i <= ipagecount; i++)
            {
                if (i > 10)
                {
                    break;
                }
                Word.Range wrg1;
                Word.Range wrg2;
                Word.Range wrg;
                wrg1 = document.GoTo(ref pWhat, ref pWhich, i);
                wrg2 = wrg1.GoToNext(Word.WdGoToItem.wdGoToPage);
                wrg  = document.Range(wrg1.Start, wrg2.Start); //指定页的范围

                string strContent = wrg.Text;                  //获取该页内容

                Console.WriteLine(strContent);

                if (strContent.Contains("答辩日期"))
                {
                    wrg.Copy();
                    P_document.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref missing);
                    P_document.ActiveWindow.Selection.Paste();
                }
            }
            P_document.ExportAsFixedFormat(@"D:\work\53002\20160823\131163876229304835\6\2062\20160822003\中共陕西省委党校2016年论文\xxxx.pdf", Word.WdExportFormat.wdExportFormatPDF);
            Console.WriteLine("over");
            P_document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            document.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            _app.Quit();
            Console.ReadKey();
        }
Ejemplo n.º 5
0
        private static int ConvertWordToPdf(string sourcePath, string targetPath)
        {
            int    result       = -1;
            object paramMissing = Type.Missing;

            WORD.Application wordApplication = null;
            WORD.Document    wordDocument    = null;
            try
            {
                object source = sourcePath;
                wordApplication               = new WORD.Application();
                wordApplication.Visible       = false;
                wordApplication.DisplayAlerts = WORD.WdAlertLevel.wdAlertsNone;
                try
                {
                    wordDocument = wordApplication.Documents.OpenNoRepairDialog(
                        source, AddToRecentFiles: false,
                        ReadOnly: true, PasswordDocument: "IN_VA_LI______D");
                }
                catch
                {
                    return(result);
                }
                if (wordDocument != null)
                {
                    WORD.WdStatistic stat = WORD.WdStatistic.wdStatisticPages;
                    int num = wordDocument.ComputeStatistics(stat);

                    wordDocument.ExportAsFixedFormat(targetPath, WORD.WdExportFormat.wdExportFormatPDF, IncludeDocProps: true);
                    result = num;
                }
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(SaveChanges: false);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(SaveChanges: false);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }
        public void DelteBlankPages()
        {

            // Get application object
            //Microsoft.Office.Interop.Word.Application WordApplication = new Microsoft.Office.Interop.Word.Application();

            // Get document object
            object Miss = System.Reflection.Missing.Value;
            object ReadOnly = false;
            object Visible = false;
            Document Doc = Globals.ThisAddIn.Application.ActiveDocument; 
            // WordApplication.Documents.Open(ref Path, ref Miss, ref ReadOnly, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Miss, ref Visible, ref Miss, ref Miss, ref Miss, ref Miss);

            // Get pages count
            Microsoft.Office.Interop.Word.WdStatistic PagesCountStat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
            int PagesCount = Doc.ComputeStatistics(PagesCountStat, ref Miss);

            //Get pages
            object What = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
            object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
            object Start;
            object End;
            object CurrentPageNumber;
            object NextPageNumber;

            for (int Index = 1; Index < PagesCount + 1; Index++)
            {
                CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                NextPageNumber = (Convert.ToInt32((Index + 1).ToString()));

                // Get start position of current page
                Start = Globals.ThisAddIn.Application.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;

                // Get end position of current page                                
                End = Globals.ThisAddIn.Application.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;

                // Get text
                Int32 inicio = Convert.ToInt32(Start.ToString());
                Int32 fin = Convert.ToInt32(End.ToString());
                if (System.Math.Abs(inicio - fin)  < 4) {
                    Doc.Range(ref Start, ref End).Delete();
                }
            }
        }
Ejemplo n.º 7
0
        public bool Open(string path)
        {
            try
            {
                Util.ConvertWord2PDF(path, Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".pdf");
            }
            catch (Exception e)
            {
            }

            //if (Global.getPPTMaximize())
            //{
            minisizeProc();
            //}


            filepath = path;
            filename = Path.GetFileName(path);
            object FileName = filepath;
            object readOnly = true;


            wordApp = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序
            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            wordApp.Visible       = true;



            try
            {
                wordDoc = wordApp.Documents.Open(ref FileName,
                                                 ref missing, ref readOnly, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing);

                if (wordApp != null && wordDoc != null)
                {
                    wordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdReadingView;
//Word.WdViewType.wdMasterView //大纲视图模式
//Word.WdViewType.wdNormalView //普通视图模式
//Word.WdViewType.wdOutlineView //和大纲视图模式类似
//Word.WdViewType.wdReadingView //阅读版式
//Word.WdViewType.wdPrintPreview //打印预览模式
//Word.WdViewType.wdPrintView //普通视图模式
//Word.WdViewType.wdWebView // 'Web版式视图


                    maximizeWordProc();
                    Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                    int nPage             = wordDoc.ComputeStatistics(stat, ref missing);
                    getPageInfo();
                    return(true);
                }
                else
                {
                    throw new Exception("openDoc failed.");
                }
            }
            catch (Exception ex)
            {
                int errorcode = 0;
                var w32ex     = ex as Win32Exception;
                if (w32ex == null)
                {
                    w32ex = ex.InnerException as Win32Exception;
                }
                if (w32ex != null)
                {
                    errorcode = w32ex.ErrorCode;
                }
                Log.Error("DocOpen exception. " + ex.Message + ", errorcode=" + errorcode);//Error HRESULT E_FAIL has been returned from a call to a COM component.

                Close();
            }
            finally
            {
            }
            return(false);
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            var docx = @"{HOME_SOURCE}\source\repos\ReportParser\ReportParser\bin\Debug\A.docx";

            try
            {
                //建立開啟Word工具
                Word.Application app = new Word.Application();
                //取得文件
                Word.Document dx = app.Documents.Open(docx);

                //Word.WdStatistic是一群列舉常數

                /*
                 * 包含:
                 *  wdStatisticCharacters	3	字元數。
                 *  wdStatisticCharactersWithSpaces	5	含空格的字元數。
                 *  wdStatisticFarEastCharacters	6	亞洲語言的字元數。
                 *  wdStatisticLines	1	行數。
                 *  wdStatisticPages	2	頁數。
                 *  wdStatisticParagraphs	4	段落數。
                 *  wdStatisticWords	0	字數。
                 */
                //取得本文件總頁數
                object           Miss           = System.Reflection.Missing.Value;
                Word.WdStatistic PagesCountStat = Word.WdStatistic.wdStatisticPages;
                int PageCount = dx.ComputeStatistics(PagesCountStat, Miss);
                Console.Out.WriteLine("Word page count : " + PageCount);

                //取得段落總數
                Word.WdStatistic PagesParagraphsStat = Word.WdStatistic.wdStatisticParagraphs;
                int PageParagraphsCount = dx.ComputeStatistics(PagesParagraphsStat, Miss);
                Console.Out.WriteLine("Paragraphs count : " + PageParagraphsCount);

                //取得Table,並檢查Table結束於哪個頁面,以及Row位於哪個頁面
                Console.Out.WriteLine("Tables count : " + dx.Tables.Count);

                foreach (Word.Table tb in dx.Tables)
                {
                    //檢查Table第3個欄位數的Cell總數,如果有合併將顯示合併後數量
                    Console.Out.WriteLine("Column 3 Cells : " + tb.Columns[3].Cells.Count);

                    Console.Out.WriteLine(" OK! ");

                    //Tabel.Uniform 屬性用來判斷是否有合併儲存格,如果有就False否則True
                    if (tb.Uniform)
                    {
                        Console.Out.WriteLine("###該表格沒有合併儲存格,所以尋列讀取!###");
                        int start = tb.Rows[1].Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                        int end   = tb.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                        Console.Out.WriteLine("Table Start Page : " + start.ToString() + " - End Page : " + end.ToString());
                        foreach (Word.Row row in tb.Rows)
                        {
                            int endpage = row.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber];
                            Console.Out.WriteLine("Row index : " + row.Index + " At Page : " + endpage.ToString());
                        }
                    }
                    else
                    {
                        Console.Out.WriteLine("###該表格有合併儲存格,所以將Table轉Cell依序讀取!###");
                        //完整頁數
                        int[] fullPages = new int[] { };
                        //計算時暫存用頁數
                        int[] tmPage = new int[] { };
                        //如果Table有合併儲存格讀取方式要將Table轉Cell依序讀取
                        Word.Range ra = tb.Range;
                        for (int i = 1; i <= ra.Cells.Count; i++)
                        {
                            try
                            {
                                Word.Cell cell    = ra.Cells[i];                                                              //取得Cell
                                int       numPage = cell.Range.Information[Word.WdInformation.wdActiveEndAdjustedPageNumber]; //取得頁數
                                int[]     st      = new int[] { numPage };                                                    //頁數準備合併前的暫存陣列物件
                                Console.Out.WriteLine("[ " + cell.RowIndex.ToString() + " - " + cell.ColumnIndex.ToString() + " ] - [ " + numPage + " ]");
                                fullPages = tmPage.Union(st).ToArray <int>();                                                 //合併
                            }
                            catch (Exception inex)
                            {
                                Console.Out.WriteLine(inex.Message);
                            }
                        }
                        Console.Out.WriteLine("Page Num : " + fullPages.Count().ToString());
                    }
                }

                //依序移動頁面,並取得頁面文字陣列
                List <string> Pages = new List <string>();
                object        What  = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
                object        Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToAbsolute;
                object        Start;
                object        End;
                object        CurrentPageNumber;
                object        NextPageNumber;

                for (int Index = 1; Index < PageCount + 1; Index++)
                {
                    CurrentPageNumber = (Convert.ToInt32(Index.ToString()));
                    NextPageNumber    = (Convert.ToInt32((Index + 1).ToString()));

                    // Get start position of current page
                    Start = app.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;

                    // Get end position of current page
                    End = app.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;

                    // Get text
                    if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
                    {
                        Pages.Add(dx.Range(ref Start, ref End).Text);
                    }
                    else
                    {
                        Pages.Add(dx.Range(ref Start).Text);
                    }
                }

                //結束關閉檔案
                dx.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                Console.Out.WriteLine(" OK! ");
            }
            catch (Exception e)
            {
                Console.Out.WriteLine(e.Message);
            }
            finally
            {
                //釋放執行緒
                Process   myProcess   = new Process();
                Process[] wordProcess = Process.GetProcessesByName("winword");
                Console.Out.WriteLine("Word process count : " + wordProcess.Count());
                foreach (Process pro in wordProcess)
                {
                    pro.Kill();
                }
            }

            string x = Console.ReadLine();
        }
Ejemplo n.º 9
0
        public bool ReadPdf(string pdfFile, ref Documents doc, ref int pages)
        {
            bool success = false;

            try
            {
                if (pdfFile.ToLower().Contains("pdf"))
                {
                    StringBuilder textBuilder = new StringBuilder();
                    PdfReader     r           = new PdfReader(pdfFile);
                    pages = r.NumberOfPages;

                    for (int i = 1; i <= pages; i++)
                    {
                        PdfReaderContentParser  parser = new PdfReaderContentParser(r);
                        ITextExtractionStrategy st     = parser.ProcessContent <SimpleTextExtractionStrategy>(i, new SimpleTextExtractionStrategy());
                        string text = st.GetResultantText().Trim('\r', '\n', '\t', (char)32, (char)160);

                        if (!string.IsNullOrEmpty(text))
                        {
                            doc.DocBodyDic.Add(i, text);
                        }
                        else
                        {
                            text = PdfTextExtractor.GetTextFromPage(r, i).Trim('\r', '\n', '\t', (char)32, (char)160);

                            if (!string.IsNullOrEmpty(text))
                            {
                                doc.DocBodyDic.Add(i, text);
                            }
                        }
                    }

                    r.Close();
                    success = true;
                }
                else if (pdfFile.ToLower().Contains("doc"))
                {
                    MsWord.Application newApp = null;
                    MsWord.Document    msdoc  = null;

                    try
                    {
                        int retry = 2;
                        while (retry > 0)
                        {
                            try
                            {
                                //newApp = (MsWord.Application)Marshal.GetActiveObject("Word.Application");
                                newApp = newApp == null ? new MsWord.Application() : newApp;
                                System.Threading.Thread.Sleep(1000);
                                //msdoc = newApp.ActiveDocument;
                                msdoc = newApp.Documents.Open(pdfFile);
                                System.Threading.Thread.Sleep(1000);
                                object             nothing = Missing.Value;
                                MsWord.WdStatistic stat    = MsWord.WdStatistic.wdStatisticPages;
                                int num = msdoc.ComputeStatistics(stat, ref nothing);

                                for (int i = 1; i <= num; i++)
                                {
                                    if (doc.DocBodyDic.ContainsKey(i))
                                    {
                                        continue;
                                    }

                                    object objWhat  = MsWord.WdGoToItem.wdGoToPage;
                                    object objWhich = MsWord.WdGoToDirection.wdGoToAbsolute;

                                    object       objPage = (object)i;
                                    MsWord.Range range1  = msdoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref nothing);
                                    MsWord.Range range2  = range1.GoToNext(MsWord.WdGoToItem.wdGoToPage);

                                    object objStart = range1.Start;
                                    object objEnd   = range2.Start;
                                    if (range1.Start == range2.Start)
                                    {
                                        objEnd = msdoc.Characters.Count;
                                    }

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("DEBUG: Path: {0}, {1}-{2}........", pdfFile, objStart, objEnd);
                                    Console.ResetColor();

                                    if ((int)objStart <= (int)objEnd)
                                    {
                                        string innerText = msdoc.Range(ref objStart, ref objEnd).Text;
                                        doc.DocBodyDic.Add(i, innerText);
                                    }
                                }

                                success = true;
                                break;
                            }
                            catch (Exception ex)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Retry to read word {0}, Exception: {1}..", pdfFile, ex.ToString());
                                Console.ResetColor();
                                System.Threading.Thread.Sleep(1000);
                                retry--;
                            }
                            finally
                            {
                                if (newApp != null)
                                {
                                    newApp.NormalTemplate.Saved = true;

                                    if (msdoc != null)
                                    {
                                        msdoc.Close(false);
                                    }

                                    newApp.Quit();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return(success);
        }
Ejemplo n.º 10
0
        private void thesisProcess_DoWork(object sender, DoWorkEventArgs e)        //Thread start edildiğinde bu fonksiyona girer.
        {
            int failCount = 0;

            thesisProcess.ReportProgress(1);            //Yüzdeyi göstermek için kullandığımız method ReportProgres(x) x sinyalini gönderir.

            Microsoft.Office.Interop.Word.Application app = new Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = app.Documents.Open(txt_thesispath.Text);         //Yukarda seçilen dosyayı Document objesinin içine yükleme işlemi.
            Word.WdStatistic stat    = Word.WdStatistic.wdStatisticPages;
            object           missing = System.Reflection.Missing.Value;
            int pageCountNumber      = doc.ComputeStatistics(stat, ref missing); //Sayfa sayısını num değişkenine atıyoruz.

            thesisProcess.ReportProgress(3);                                     //Yüzde 3

            //İlk sayfa sayısını kontrol ediyoruz.
            if (pageCountNumber < 40 || pageCountNumber > 180)
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İdeal tez uzunluğu 40 - 180 sayfa arasında olmalıdır! Mevcut sayfa sayısı:" + pageCountNumber);
                }));
            }

            float leftmargin   = doc.PageSetup.LeftMargin;   //Sol boşluk,
            float rightmargin  = doc.PageSetup.RightMargin;  //Sağ boşluk,
            float topMargin    = doc.PageSetup.TopMargin;    //Üst boşluk,
            float bottomMargin = doc.PageSetup.BottomMargin; //Alt boşluk değerleri dokümandan okunuyor.

            if (rightmargin != 70.9f)                        //Sağ boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sağ kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (bottomMargin != 70.9f)            //Alt boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Alt kenar boşluğu 2.5 cm olmalıdır!");
                }));
            }

            if (leftmargin != 92.15f)            //Sol boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Sol kenar boşluğu 3.25 cm olmalıdır!");
                }));
            }

            if (topMargin != 85.05f)            //Üst boşluğun kontrolü.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Üst kenar boşluğu 3.0 cm olmalıdır!");
                }));
            }
            thesisProcess.ReportProgress(5);

            int paragraphcount = doc.Paragraphs.Count;

            int counter            = 0;
            int timesnewromancount = 0;
            int elevenpuntocounter = 0;

            bool onsozexists      = false;
            bool icindekilerexist = false;
            bool ozetexists       = false;
            bool kaynakExists     = false;
            bool beyanexists      = false;


            bool abstractExists              = false;
            bool sekilListesiexists          = false;
            bool eklerlistesiexists          = false;
            bool simgelerveKisaltmalarExists = false;

            int ShapesCount   = doc.InlineShapes.Count;
            int inShapesCount = doc.Shapes.Count;

            int tablocount = 0;

            int sekilcount = 0;

            Hashtable htSekil = new Hashtable();
            Hashtable htTablo = new Hashtable();

            double sekilCounter = 0;
            double tabloCounter = 0;

            foreach (Paragraph objParagraph in doc.Paragraphs)               //Paragrafların her biri tek tek okunup objParagraph objesinin içine atılıyor.
            {
                if (objParagraph.Range.Font.Name == "Times New Roman")       //Eğer font Times New Roman ise;
                {
                    timesnewromancount++;                                    //Times New Roman sayısı bir arttırılıyor.
                }
                if (objParagraph.Range.Font.Size == 11)                      //Font size'ı 11 ise;
                {
                    elevenpuntocounter++;                                    //Font size'ı kontrol eden değişkenimiz bir arttırılıyor.
                }
                if (objParagraph.Range.Text.Trim() == Constants.ICINDEKILER) //İçindekiler texti paragrafta bulundu mu?
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ICINDEKILER) + Constants.ICINDEKILER.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'İÇİNDEKİLER'");                            //Hata ekrana bastırılır..
                        }));
                    }

                    icindekilerexist = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.OZET)               //Özet texti
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.OZET) + Constants.OZET.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'Özet'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    ozetexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ONSOZ)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ONSOZ) + Constants.ONSOZ.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ÖNSÖZ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    onsozexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.KAYNAKLAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.KAYNAKLAR) + Constants.KAYNAKLAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'KAYNAKLAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    kaynakExists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.ABSTRACT)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.ABSTRACT) + Constants.ABSTRACT.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ABSTRACT'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    abstractExists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.BEYAN)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.BEYAN) + Constants.BEYAN.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'BEYAN'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    beyanexists = true;
                }
                if (objParagraph.Range.Text.Trim() == Constants.SEKILLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKILLERLISTESI) + Constants.SEKILLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;
                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'ŞEKİLLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    sekilListesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.EKLERLISTESI)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.EKLERLISTESI) + Constants.EKLERLISTESI.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'EKLER LİSTESİ'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    eklerlistesiexists = true;
                }

                if (objParagraph.Range.Text.Trim() == Constants.SIMGELERVEKISALTMALAR)
                {
                    object start        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR);
                    object startplusone = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + 1;

                    object end = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SIMGELERVEKISALTMALAR) + Constants.SIMGELERVEKISALTMALAR.Length;


                    Word.Range rangeFirstChar = doc.Range(ref start, ref startplusone);
                    Word.Range rangeothers    = doc.Range(ref startplusone, ref end);

                    float textsizefirst  = rangeFirstChar.Font.Size;
                    float textsizeothers = rangeothers.Font.Size;

                    if (textsizefirst != 16)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("İlk harf 16 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }


                    if (textsizeothers != 13)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Başlığın ilk harfinden sonra gelen harfler 13 punto olmalı! Bölüm :'SİMGELER VE KISALTMALAR'");                            //Hata ekrana bastırılır..
                        }));
                    }
                    simgelerveKisaltmalarExists = true;
                }

                if (objParagraph.Range.Text.Contains(Constants.SEKIL))
                {
                    //Şekil 2.3.
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.SEKIL) + Constants.SEKIL.Length + 5;
                    Word.Range rangesekil = doc.Range(ref start, ref end);

                    bool isSekild = Helper.TextIsSekil(rangesekil.Text);

                    if (isSekild && !htSekil.ContainsKey(rangesekil.Text))                  //Eğer hashtable'da şekil yoksa kontrolü yapılıyor.
                    {
                        sekilcount++;                                                       //Yoksa şekil sayacı bir arttırılıyor.
                        htSekil[rangesekil] = rangesekil.Text;                              //Hashtable'ın içine şekil atılıyor.

                        double sekilNumber = Double.Parse(rangesekil.Text.Substring(6, 3)); // 4.3

                        if (sekilNumber < sekilCounter)                                     //sekilCounter en son şeklin numarasını tutar. Eğer yeni gelen şekil son şekilden küçükse hata vardır.
                        {
                            failCount++;
                            this.Invoke(new MethodInvoker(() =>
                            {
                                this.listResults.Items.Add("Şekil numaraları sırayla olmalıdır!");                                //Hata ekrana bastırılır..
                            }));
                        }
                        else
                        {
                            sekilCounter = sekilNumber;
                        }
                    }

                    if (isSekild && rangesekil.Font.Size < 10)                    //Eğer şekil gelmiş ve font size'ı 10'dan küçükse ekrana hata bastırılır.
                    {
                        failCount++;

                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Şekil kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }
                //BEYAN
                if (objParagraph.Range.Text.Contains(Constants.TABLO))                //Şekil için yapılan yukardaki bloğun tamamı tablo için de yapılıyor.
                {
                    object     start      = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO);
                    object     end        = objParagraph.Range.Start + objParagraph.Range.Text.IndexOf(Constants.TABLO) + Constants.TABLO.Length + 5;
                    Word.Range rangetablo = doc.Range(ref start, ref end);

                    bool istablo = Helper.TextIsTablo(rangetablo.Text);
                    if (istablo && !htTablo.ContainsKey(rangetablo.Text))
                    {
                        tablocount++;
                        htTablo[rangetablo] = rangetablo.Text;
                    }

                    if (istablo && rangetablo.Font.Size < 10)
                    {
                        failCount++;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.listResults.Items.Add("Tablo kısımları en az 10 boyutunda olmalı!");
                        }));
                    }
                }

                thesisProcess.ReportProgress(5 + (95 * counter / doc.Paragraphs.Count));            // Progress hesaplama yüzde hesaplama Toplam paragraf sayısının mevcut paragraf indexine oranını buluyoruz. Bunu yüzde olarak gösteriyoruz.

                counter++;
            }


            if ((ShapesCount + inShapesCount) < (tablocount + sekilcount)) //Eğer dokümandaki shape countu tablo ve şekil count'ından küçükse o zaman tüm tablo ve şekillere isim verilmemiştir anlamına gelir.
            {                                                              //Bu durumda ekrana hata bastırılır.
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tüm şekil ve tabloların altına Şekil ve Tablo numarası yazılmalıdır!");
                }));
            }

            if (!beyanexists)            //Yukarıdaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("BEYAN bölümü eksik!");
                }));
            }
            if (!onsozexists) //Önsöz değişkenine yukarıda atama yapıldı. Eğer atamalar sonucunda değişken true'ya çevrilmemişse;
            {                 //bu kod işler.
                failCount++;  //fail sayısı bir arttırılır.

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖNSÖZ bölümü eksik!");                    // Önsöz bölümü eksik hatası ekrana bastırılır.
                }));
            }
            if (!icindekilerexist) //Eğer içindekiler değişkenine true atanmadıysa;
            {                      //hata ekrana bastırılır.
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("İÇİNDEKİLER bölümü eksik!");
                }));
            }
            if (!ozetexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ÖZET bölümü eksik!");
                }));
            }
            if (!abstractExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ABSTRACT bölümü eksik!");
                }));
            }


            if (!sekilListesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("ŞEKİLLER LİSTESİ bölümü eksik!");
                }));
            }
            if (!eklerlistesiexists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("EKLER LİSTESİ bölümü eksik!");
                }));
            }



            if (!simgelerveKisaltmalarExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("SIMGELER VE KISALTMALAR bölümü eksik!");
                }));
            }
            if (!kaynakExists)            //Yukardaki gibi
            {
                failCount++;
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("KAYNAKLAR bölümü eksik!");
                }));
            }
            if (timesnewromancount * 2 < paragraphcount)            //Eğer tezin yarısından çoğu Times New Roman ile yazılmamışsa ekrana hata bastırılır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin yazım fontu Times New Roman olmalıdır! Tezdeki Times New Roman oranı = %" + 100 * timesnewromancount / paragraphcount);
                }));
            }

            if (elevenpuntocounter * 1.5 < paragraphcount)            //Tez içeriğindeki yazıların boyutu 11 punto olmalıdır.
            {
                failCount++;

                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezin font büyüklüğü 11 punto olmalıdır! Tezde bulunan 11 punto oranı= %" + 100 * elevenpuntocounter / paragraphcount);
                }));
            }


            if (failCount == 0)            //Eğer hata sayısı 0 ise tezinizde hata bulunamadı diye mesaj gösteriyoruz.
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add("Tezinizde hiçbir hata bulunamadı!");
                }));
            }
            else
            {
                this.Invoke(new MethodInvoker(() =>
                {
                    this.listResults.Items.Add(string.Format("Tezinizde bulunan hata başlığı sayısı:{0}", failCount));                   //Hata sayısı 0'dan farklıysa da tezde bulunan toplam hata sayısı gösteriliyor.
                }));
            }

            doc.Close();
            doc = null;
            //return num;
        }
Ejemplo n.º 11
0
        //экспорт в шаблон Word
        private void button6_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("" + My.oborudovanie.ToString() );
            //if (textBox2.Text == "")
            //{
            //    MessageBox.Show("Не выбран(ы) испытатель(ли)!");
            //    return;
            //}

            //MessageBox.Show("" + My.poveritelListLength);
            //dbCon.Close();
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc = new Microsoft.Office.Interop.Word.Document();
            object missing = Type.Missing;

            //Объявляем новый экземпляр класса Stopwatch
            //запускаем
            Stopwatch testStopwatch = new Stopwatch();

            testStopwatch.Start();

            if (dataGridView1.Rows.Count != 0)
            {
                object fileName   = Directory.GetCurrentDirectory() + @"\ОА\tmpl.doc";
                object falseValue = false;
                object trueValue  = true;

                doc = app.Documents.Open(ref fileName, ref missing, ref falseValue,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing, ref missing, ref missing,
                                         ref missing, ref missing, ref missing);
                //app.Visible = true;

                //exception();
                //string[] txt = { label1.Text, DateTime.Now.ToLongDateString(), label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, /*label13.Text*/ label18.Text, label19.Text, label20.Text, label21.Text, label22.Text, label14.Text, label15.Text };
                string[] txt     = { label1.Text, label26.Text, /*DateTime.Now.ToLongDateString(),*/ label2.Text, label3.Text, /*label4.Text,*/ label5.Text, label4.Text, label6.Text, label23.Text, label7.Text, label8.Text, label9.Text, label10.Text, label11.Text, label12.Text, label13.Text /*, label18.Text, label19.Text, label20.Text, label21.Text, label22.Text*/ /*, label14.Text, label15.Text*/ };
                string[] FindObj = { "$num$", "$date$", /*"$date$",*/ "$zakazchik$", "$adress_zakazchika$", /*"$postavshik$",*/ "$name_izgotov$", "$adress_izgotov$", "$product_name$", "$product_group$", "$name$", "$proba$", "$date_time_postuplenia$", "$date_exe$", "$osnovanie$", "$nd$", "$conditions$" /*, "$temperature$", "$vlazhnost$","$davlenie$", "$elmagpole$", "$magpole$"*/ /*, "$dolznost$", "$sotrudnik$"*/ };

                int n = 0;
                while (n < FindObj.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = FindObj[n];
                    object replaceWithNUM = txt[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;


                //string poveritelListFind = "$poveritelList$";
                for (int nn = 0; nn < My.poveritelListLength; nn++)
                {
                    if (My.poveritelList[nn] == "")
                    {
                        nn++;
                    }
                    else
                    {
                        textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    }
                }

                //Очищаем параметры поиска
                app.Selection.Find.ClearFormatting();
                app.Selection.Find.Replacement.ClearFormatting();

                //Задаём параметры замены и выполняем замену.
                object findTextNUM2    = "$poveritelList$";
                object replaceWithNUM2 = textBox2.Text;
                object replaceNUM2     = 2;

                app.Selection.Find.Execute(ref findTextNUM2, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM2, ref replaceNUM2, ref missing, ref missing, ref missing, ref missing);


                //string oborudovanieListFind = "$oborudovanie$";
                for (int nn = 0; nn < My.oborudovanieListLength; nn++)
                {
                    //textBox2.AppendText(My.poveritelList[nn] + "\r\r");
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM3    = "$oborudovanie$";
                    object replaceWithNUM3 = "- " + My.oborudovanieList[nn] + ";\r$oborudovanie$";
                    object replaceNUM3     = 2;

                    app.Selection.Find.Execute(ref findTextNUM3, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM3, ref replaceNUM3, ref missing, ref missing, ref missing, ref missing);
                }

                //Задаём параметры замены и выполняем замену.
                object findTextNUM4    = "$oborudovanie$";
                object replaceWithNUM4 = "";
                object replaceNUM4     = 2;

                app.Selection.Find.Execute(ref findTextNUM4, ref missing, ref missing, ref missing,
                                           ref missing, ref missing, ref missing, ref missing, ref missing,
                                           ref replaceWithNUM4, ref replaceNUM4, ref missing, ref missing, ref missing, ref missing);

                Microsoft.Office.Interop.Word.Table table = doc.Tables[2];

                int i;

                for (i = 1; i < dataGridView1.Rows.Count + 1; i++)
                {
                    table.Rows.Add();
                    table.Cell(i + 2, 1).Range.Text = i.ToString();          //нумерация

                    for (int j = 1; j < dataGridView1.ColumnCount - 1; j++)  //цикл вставки dGV
                    {
                        //table.Cell(i + 2, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                        table.Cell(i + 3, j + 1).Range.Text = dataGridView1.Rows[i - 1].Cells[j].Value.ToString();
                    }
                }

                //количество страниц/листов
                Word.WdStatistic stat = Word.WdStatistic.wdStatisticPages;
                double           x    = doc.ComputeStatistics(stat, ref missing); //страницы
                string           y    = Math.Ceiling(x / 2).ToString("G17");      //листы
                //label16.Text = x.ToString("G17");

                //поиск и вставка x&y
                string[] xy     = { x.ToString("G17"), y };
                string[] Findxy = { "$x$", "$y$" };

                while (n < Findxy.Length)
                {
                    //Очищаем параметры поиска
                    app.Selection.Find.ClearFormatting();
                    app.Selection.Find.Replacement.ClearFormatting();

                    //Задаём параметры замены и выполняем замену.
                    object findTextNUM    = Findxy[n];
                    object replaceWithNUM = xy[n];
                    object replaceNUM     = 2;

                    app.Selection.Find.Execute(ref findTextNUM, ref missing, ref missing, ref missing,
                                               ref missing, ref missing, ref missing, ref missing, ref missing,
                                               ref replaceWithNUM, ref replaceNUM, ref missing, ref missing, ref missing, ref missing);
                    n++;
                }
                n = 0;

                DialogResult res = MessageBox.Show("Экспорт завершен. При нажатии ДА будет открыт сгенерированный файл, при нажатии НЕТ произойдет автоматическое сохранение файла и его открытие.", "Экспорт в Excel", MessageBoxButtons.YesNoCancel);

                if (res == DialogResult.Yes)    //открытие сгенерированного файла
                {
                    try
                    {
                        //Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\ОА\tmpl.doc";
                        //object newfileName = Directory.GetCurrentDirectory() + @"\ОА\протокол №" + label1.Text + ".doc";
                        app.Visible = true;

                        //doc = app.Documents.Open(ref fileName, ref missing, ref trueValue,
                        //                         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);
                        //// Закрываем родительскую форму
                        //Hide();
                        MessageBox.Show("Экспорт успешно завершен, протокол открыт. При необходимости, сохраните протокол.");

                        /*
                         * string lastNumDir = Directory.GetCurrentDirectory() + @"\ОА\последний_номер.txt";
                         * string lastNumUPD = label1.Text;
                         * System.IO.File.WriteAllText(lastNumDir, lastNumUPD);
                         */
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.No)     //автоматическое сохранение файла
                {
                    try
                    {
                        object Target  = (Directory.GetCurrentDirectory() + @"\ОА\Протоколы\" + label1.Text + ".doc"); // куда сохранить
                        object format_ = Word.WdSaveFormat.wdFormatDocumentDefault;
                        //Сохранение файла
                        doc.SaveAs(ref Target, ref format_,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing);

                        //object falseValue = false;
                        //object trueValue = true;

                        doc = app.Documents.Open(ref Target, ref missing, ref falseValue,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing, ref missing, ref missing,
                                                 ref missing, ref missing, ref missing);
                        ///
                        ///колонтитулы
                        ///

                        //верний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("");
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //верхний колонтитул
                        //остальные страницы
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                            doc.ActiveWindow.Selection.TypeText("ФБУ «Нижегородский ЦСМ» ИЦ «НИЖЕГОРОДСИСПЫТАНИЯ»          Протокол №" + label1.Text + " от " + label26.Text);
                            doc.ActiveWindow.Selection.Fields.Add(s.Range);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekFirstPageFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        //нижний колонтитул
                        //первая страница
                        foreach (Word.Section section in app.ActiveDocument.Sections)
                        {
                            //нижний колонтитул
                            Object oMissing = System.Reflection.Missing.Value;
                            Microsoft.Office.Interop.Word.Selection s = app.Selection;

                            // код для номеров страницы
                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
                            s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                            doc.ActiveWindow.Selection.TypeText("страница ");
                            object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //текущая страница
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);

                            doc.ActiveWindow.Selection.TypeText(" из ");
                            object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //всего страниц
                            doc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);

                            doc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //выход из колонтитула
                        }

                        app.Visible = true;

                        MessageBox.Show("Экспорт успешно завершен, протокол сохранен под номером " + label1.Text);
                    }
                    catch
                    {
                        MessageBox.Show("ooooops...! что-то пошло не так. Пожалуйста обратитесь в службу поддержки");
                    }
                }

                if (res == DialogResult.Cancel) //отмена
                {
                    MessageBox.Show("Сохранение результатов экспорта отменено");
                    ((Microsoft.Office.Interop.Word._Application)app).Quit(false, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
                }
                //Останавливаем
                testStopwatch.Stop();

                //Теперь можем смотреть время выполнения операции
                TimeSpan tSpan; tSpan = testStopwatch.Elapsed;
                //MessageBox.Show("Время выполнения операции - " + tSpan.ToString()); //время выполнения операции
            }
            else
            {
                MessageBox.Show("Не открыта таблица для запроса");
            }
            exit = false;



            Hide();
            Form3 form3 = new Form3();

            form3.Show();
        }
Ejemplo n.º 12
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count <= 1)
            {
                return;
            }
            Object filename              = "test.docx";
            Object filefullname          = @theStrPath[0];
            Object confirmConversions    = Type.Missing;
            Object readOnly              = false;
            Object addToRecentFiles      = Type.Missing;
            Object passwordDocument      = Type.Missing;
            Object passwordTemplate      = Type.Missing;
            Object revert                = Type.Missing;
            Object writePasswordDocument = Type.Missing;
            Object writePasswordTemplate = Type.Missing;
            Object format                = Type.Missing;
            Object encoding              = Type.Missing;
            Object visible               = Type.Missing;
            Object openConflictDocument  = Type.Missing;
            Object openAndRepair         = Type.Missing;
            Object documentDirection     = Type.Missing;
            Object noEncodingDialog      = Type.Missing;

            Microsoft.Office.Interop.Word.Application theAppWord  = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    theDocument = null;
            MSWord.Document tempDocument = null;
            theDocument = theAppWord.Documents.Open(ref filefullname, ref confirmConversions, ref readOnly, ref addToRecentFiles,
                                                    ref passwordDocument, ref passwordTemplate, ref revert,
                                                    ref writePasswordDocument, ref writePasswordTemplate,
                                                    ref format, ref encoding, ref visible, ref openConflictDocument,
                                                    ref openAndRepair, ref documentDirection, ref noEncodingDialog
                                                    );

            theAppWord.Visible = false;
            //先关闭打开的文档(注意saveChanges选项)
            Object saveChanges    = MSWord.WdSaveOptions.wdSaveChanges;
            Object originalFormat = Type.Missing;
            Object routeDocument  = Type.Missing;

            object docStart = null;
            object docEnd   = null;
            object start    = null;
            object end      = null;

            for (int i = 1; i < theStrPath.Count; i++)
            {
                progressBar1.Value = i * 100 / theStrPath.Count;
                filefullname       = @theStrPath[i];
                readOnly           = true;
                tempDocument       = theAppWord.Documents.Open(ref filefullname, ref confirmConversions, ref readOnly, ref addToRecentFiles,
                                                               ref passwordDocument, ref passwordTemplate, ref revert,
                                                               ref writePasswordDocument, ref writePasswordTemplate,
                                                               ref format, ref encoding, ref visible, ref openConflictDocument,
                                                               ref openAndRepair, ref documentDirection, ref noEncodingDialog
                                                               );


                theDocument.Sections.Add();
                docStart = theDocument.Content.End - 1;
                docEnd   = theDocument.Content.End;

                start = tempDocument.Content.Start;
                end   = tempDocument.Content.End;
                //tempDocument.Range(ref start, ref end).Copy();

                tempDocument.Activate();
                theAppWord.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;
                theAppWord.Selection.WholeStory();
                theAppWord.Selection.Copy();

                //计算word文档页数

                MSWord.WdStatistic tempstart = MSWord.WdStatistic.wdStatisticPages;
                int num = tempDocument.ComputeStatistics(tempstart);

                System.Diagnostics.Debug.Print("--------------------" + num);
                theDocument.Activate();
                //theAppWord.Selection.EndKey(MSWord.WdUnits.wdStory);
                if (num > 10)
                {
                    IntPtr p = FindWindowEx(System.IntPtr.Zero, System.IntPtr.Zero, null, theAppWord.Caption);
                    SetFocus(p);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.End), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.End), 0, 2, 0);

                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.V), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0, 2, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.V), 0, 2, 0);
                    System.Threading.Thread.Sleep(500);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.N), 0, 0, 0);
                    keybd_event(Convert.ToByte(System.Windows.Forms.Keys.N), 0, 2, 0);
                    //byte[] ch = (ASCIIEncoding.ASCII.GetBytes());
                    //SendMessage(p, WM_CHAR, Convert.ToByte(System.Windows.Forms.Keys.ControlKey), 0);
                    //SendMessage(p, WM_CHAR, Convert.ToByte(System.Windows.Forms.Keys.V), 0);
                }
                else
                {
                    theAppWord.Selection.PasteAndFormat(MSWord.WdRecoveryType.wdUseDestinationStylesRecovery);
                }


                //theDocument.Range(ref docStart, ref docEnd).PasteAndFormat(MSWord.WdRecoveryType.wdUseDestinationStylesRecovery);

                saveChanges = MSWord.WdSaveOptions.wdDoNotSaveChanges;
                ((MSWord._Document)tempDocument).Close(ref saveChanges, ref originalFormat, ref routeDocument);
            }

            saveChanges = MSWord.WdSaveOptions.wdSaveChanges;
            ((MSWord._Document)theDocument).Close(ref saveChanges, ref originalFormat, ref routeDocument);

            ((MSWord._Application)theAppWord).Quit(Type.Missing, Type.Missing, Type.Missing);

            Kill(theAppWord);
            progressBar1.Value = 100;
            MessageBox.Show("恭喜您,Word文件合标完成!", "合并成功!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }
Ejemplo n.º 13
0
        public RtfParser(string path)
        {
            Application word = new Application();

            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            Frames frames = null;

            object fileName = path;

            // Define an object to pass to the API for missing parameters
            object missing = System.Type.Missing;

            try
            {
                doc = word.Documents.Open(ref fileName,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing, ref missing,
                                          ref missing, ref missing, ref missing);

                this.Company   = new Dictionary <string, string>();
                this.Documents = new List <Dictionary <string, string> >();
                this.Rows      = new List <Dictionary <string, string> >();

                frames = doc.Frames;

                //Example delivery note "005.rtf":
                //
                //       <Company>
                //   4 -  <Name>FTORR Corp.</Name>
                //   5 -  <Address>5283 Laoreet St.</Address>
                //   6 -  <Zip>71272</Zip>
                //   6 -  <City>Bangor</City>
                //   6 -  <State>ME</State>
                //        <Country>United States</Country>
                //   15 - <FiscalCode>06392640964</FiscalCode>
                //        <VatCode>06392640964</VatCode>
                //       </Company>
                //       <Documents>
                //         <Document>
                //   50 -    <CustomerCode>5476</CustomerCode>
                //   19 -    <SoldToName>Pellentesque Consulting</SoldToName>
                //   18 -    <ShipToName>Neque Et Associates</ShipToName>
                //   21 -    <ShipToAddress>Ap #327-6373 Fusce St.</ShipToAddress>
                //   23 -    <ShipToZip>47019</ShipToZip>
                //   23 -    <ShipToCity>Essex</ShipToCity>
                //   23 -    <ShipToState>VI</ShipToState>


                //   37 -    <Date>2019-01-22</Date> //Document date


                //   39 -    <Number>152</Number>
                //   54 -    <TransportReason>Sale</TransportReason>
                //   145 -    <TransportDateTime>22/01/2019 17:28</TransportDateTime>
                //           <Rows>
                //             <Row>
                //               <Code>2014</Code>
                //               <Description>Glipizide</Description>
                //               <Qty>12,00</Qty>
                //             </Row>
                //              ...
                //         </Document>
                //       </Documents>
                //
                // Note: not all fields are used.

                this.Company.Add("Name", frames[4].Range.Text);

                this.Company.Add("Address", frames[5].Range.Text);

                string[] companyLocationZipCityState = frames[6].Range.Text.Split(' ');

                this.Company.Add("Zip", companyLocationZipCityState[0]);

                StringBuilder City = new StringBuilder();

                for (int i = 1; i < companyLocationZipCityState.Length - 1; i++)
                {
                    City.Append(companyLocationZipCityState[i]);

                    if (i != companyLocationZipCityState.Length - 2)
                    {
                        City.Append(" ");
                    }
                }

                this.Company.Add("City", City.ToString());

                this.Company.Add("State", companyLocationZipCityState[companyLocationZipCityState.Length - 1]);

                this.Company.Add("Country", "United States");

                //this.Company.Add("FiscalCode", frames[15].Range.Text);

                //this.Company.Add("VatCode", frames[15].Range.Text);

                Dictionary <string, string> document = new Dictionary <string, string>();

                document.Add("CustomerCode", frames[50].Range.Text);

                ExcelSheetParser xlsParser
                    = new ExcelSheetParser(string.Format(@"{0}",
                                                         CodeManager.CustomerDataFilePath));

                this.Discounts = xlsParser.GetDiscounts(document["CustomerCode"]);

                document.Add("CustomerName", frames[19].Range.Text);

                document.Add("DeliveryName", frames[18].Range.Text);

                City = new StringBuilder();

                string[] deliveryLocationZipCityState = frames[23].Range.Text.Split(' ');

                for (int i = 1; i < deliveryLocationZipCityState.Length - 1; i++)
                {
                    City.Append(deliveryLocationZipCityState[i]);

                    if (i != deliveryLocationZipCityState.Length - 2)
                    {
                        City.Append(" ");
                    }
                }

                document.Add("DeliveryAddress", frames[21].Range.Text);

                document.Add("DeliveryZip", deliveryLocationZipCityState[0]);

                document.Add("DeliveryCity", City.ToString());

                document.Add("DeliveryState", deliveryLocationZipCityState[deliveryLocationZipCityState.Length - 1]);

                // document.Add("DocumentType", "D");

                string[] documentDateArray = frames[37].Range.Text.Split('/');
                Array.Reverse(documentDateArray);
                string documentDateString = String.Join("-", documentDateArray);

                document.Add("Date", documentDateString);

                document.Add("Number", (frames[39].Range.Text).Trim());

                //document1.Add("TransportReason", frames[54].Range.Text);

                //document1.Add("TransportDateTime", frames[145].Range.Text);

                this.Documents.Add(document);

                //Calculate number of pages
                Microsoft.Office.Interop.Word.WdStatistic numOfPagesStat
                    = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;

                int numOfPages  = doc.ComputeStatistics(numOfPagesStat, ref missing);
                int currentPage = 1;

                int itemCodePos = 0;

                //Repeat code in the "while" block for each page
                while (currentPage <= numOfPages)
                {
                    //First item code (in each page) is always at the 62th position.
                    if (frames[62].Range.Text != null) //Check whether items exist
                    {
                        //In each page, the first item position can be found at multiple of 62
                        itemCodePos += 62;

                        int loopCounter = 0;

                        //frames[itemCodePos+4] is the "Qty" column of the first item. If this is empty, it means customer name and
                        //address lines have been incorrectly used as the article description for one or more articles.
                        while (frames[itemCodePos + 4].Range.Text == null)
                        {
                            //Let's explain this with an example: (see example file: "customer-data-in-description-field.rtf"
                            //
                            //if three lines of article description contain:
                            //
                            //   DESCRIPTION
                            //
                            //   Eu Corp.
                            //   3019 A, Av.
                            //   23807 Tulsa OK
                            //
                            //then: itemCodePos+3 is: "3019 A, Av."
                            //      itemCodePos+6 is: "23807 Tulsa OK"
                            //
                            //and so on incrementing by multiples of three
                            itemCodePos += 3;

                            //We know when at the next iteration we'll find the first item code, because at that
                            //point frames[itemCodePos + 4] is going to contain the first item description, hence it will
                            //not be empty anymore
                            if (frames[itemCodePos + 4].Range.Text != null)
                            {
                                //Again, referring to previous example, if frames[itemCodePos + 4] contains an item description,
                                //this means we are on the last line of the customer address (in the description column).
                                //
                                //If this is the last line of a customer address, then moving three positions onward, we'll find
                                //our first item code.
                                //
                                //So, here we move where the item code is and before exiting the loop.
                                itemCodePos += 3;

                                //Before exiting the loop, warn the user that the item description incorrectly contains the personal
                                //data of a customer
                                System_Windows_Forms.MessageBox.Show("Warning: the customer data in this delivery note has been incorrectly placed in the \"DESCRIPTION\" field of one or more items.\n\nThe XML file will be generated anyway.",
                                                                     "Document not well formed",
                                                                     System_Windows_Forms.MessageBoxButtons.OK,
                                                                     System_Windows_Forms.MessageBoxIcon.Warning);
                            }

                            //Just in case, if for any reason the code logic here turns into an infinite loop, exit
                            //after max 10000 iterations
                            if (loopCounter > 10000)
                            {
                                throw new Exception("error while fetching item data.");
                            }

                            loopCounter++;
                        }

                        int itemDescriptionPos = itemCodePos + 1;

                        //Oddly enough, quantity for the first item comes before its code
                        int itemQtyPos = itemCodePos - 1;

                        do
                        {
                            Dictionary <string, string> row = new Dictionary <string, string>();

                            string itemCode = frames[itemCodePos].Range.Text;

                            row.Add("Code", itemCode);
                            row.Add("Description", frames[itemDescriptionPos].Range.Text);
                            row.Add("Qty", frames[itemQtyPos].Range.Text);
                            row.Add("Discounts", this.Discounts);

                            this.Rows.Add(row);

                            if ((frames[itemDescriptionPos + 2].Range.Text != null) &&
                                (frames[itemDescriptionPos + 2].Range.Text.Trim().ToUpper() == "EXTERNAL PACKAGE"))
                            {
                                //itemDescriptionPos + 2 is the position of the frame containg the string: "EXTERNAL PACKAGE".
                                //Add 15 to it to move to the last frame in the page (it's in the footer on the right and i's empty)
                                //Remember, in each page the first item position can be found at multiple of 62
                                itemCodePos = itemDescriptionPos + 2 + 15;

                                //Used for testing:
                                //string testValue = frames[nextItemCodePos].Range.Text ?? "NULL";

                                break;
                            }

                            itemCodePos       += 5;
                            itemDescriptionPos = itemCodePos + 1;
                            itemQtyPos         = itemCodePos - 1;
                        } while (true);
                    }

                    currentPage++;
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                //Release com objects to fully kill Word process from running in
                //the background
                CodeManager.ReleaseComObject(frames);
                frames = null;

                //Close and release
                ((_Document)doc).Close();
                CodeManager.ReleaseComObject(doc);
                doc = null;

                //Quit and release
                if (word != null)
                {
                    ((_Application)word).Quit();
                }

                CodeManager.ReleaseComObject(word);
                word = null;

                GC.Collect();
            }
        }