Example #1
0
        public void insert(object aFileName, string aPicName, string aBookMark)
        {
            Microsoft.Office.Interop.Word.Application worldApp = new Microsoft.Office.Interop.Word.Application();

            Microsoft.Office.Interop.Word.Document doc = null;
            object oMissing = System.Reflection.Missing.Value;

            doc = worldApp.Documents.Open(ref aFileName,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                          ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            try
            {
                                //定义该插入图片是否为外部链接
                                object linkToFile = false;
                                //定义插入图片是否随word文档一起保存
                                object saveWithDocument = true;

                //图片
                string replacePic = aPicName;
                if (doc.Bookmarks.Exists(aBookMark) == true)
                {
                    object bookMark = aBookMark;
                                        //查找书签
                                        doc.Bookmarks.get_Item(ref bookMark).Select();

                                        //设置图片位置
                                        worldApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                    //在书签的位置添加图片
                    InlineShape inlineShape = worldApp.Selection.InlineShapes.AddPicture(replacePic, ref linkToFile, ref saveWithDocument, ref oMissing);
                                        //设置图片大小
                                        inlineShape.Width = 100;
                    inlineShape.Height = 100;
                    inlineShape.Select();
                    inlineShape.ConvertToShape().IncrementLeft(-60.0f);


                    //将图片设置浮动在文字上方
                    inlineShape.ConvertToShape().WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapFront;
                }
            }
            catch
            {
                doc.Saved = false;
                                //word文档中不存在该书签,关闭文档
                                doc.Close(ref oMissing, ref oMissing, ref oMissing);
            }
        }
Example #2
0
        /// <summary>
        /// Write an image to the end of the active document
        /// </summary>
        /// <param name="filePath"></param>
        public WordController WriteImage(FilePath filePath)
        {
            W.Document  doc    = ActiveDocument;
            Range       range  = EndRange();
            InlineShape iShape = doc.InlineShapes.AddPicture(filePath.Path, false, true, range);

            W.Shape shape = iShape.ConvertToShape();
            shape.Left            = (float)WdShapePosition.wdShapeCenter;
            shape.WrapFormat.Type = WdWrapType.wdWrapInline;
            iShape.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            return(this);
        }
Example #3
0
        public void InsertPictureStatic(string picPath, int width, int height)
        {
            object      missing          = System.Reflection.Missing.Value;
            object      LinkToFile       = false;
            object      SaveWithDocument = true;
            object      Anchor           = oWordApplic.Selection.Range;
            InlineShape inlineShape      = oWordApplic.ActiveDocument.InlineShapes.AddPicture(picPath, ref LinkToFile, ref SaveWithDocument, ref Anchor);

            inlineShape.Width  = width;  // 图片宽度
            inlineShape.Height = height; // 图片高度
            Shape cShape = inlineShape.ConvertToShape();

            cShape.WrapFormat.Type = WdWrapType.wdWrapFront;
            //oWordApplic.Selection.InlineShapes.AddPicture(picPath, ref missing, ref missing, ref missing);
        }
Example #4
0
        public void InsertPicture(string fileName)
        {
            var         inlineShapes = _range.InlineShapes;
            InlineShape shape        = (InlineShape)inlineShapes.GetType()
                                       .InvokeMember("AddPicture", BindingFlags.InvokeMethod, null, inlineShapes,
                                                     new object[] { fileName });

            shape.LockAspectRatio = MsoTriState.msoCTrue;
            shape.Width           = 140;
            var s = shape.ConvertToShape();

            s.WrapFormat.Type         = WdWrapType.wdWrapSquare;
            s.WrapFormat.DistanceLeft = 0;
            s.WrapFormat.DistanceTop  = 0;
            s.Left = 0;
            s.Top  = 0;
        }
Example #5
0
        public void InsertPictureAndHint(string picPath, string hint, int width, int height)
        {
            object      missing          = System.Reflection.Missing.Value;
            object      LinkToFile       = false;
            object      SaveWithDocument = true;
            object      Anchor           = oWordApplic.Selection.Range;
            InlineShape inlineShape      = oWordApplic.ActiveDocument.InlineShapes.AddPicture(picPath, ref LinkToFile, ref SaveWithDocument, ref Anchor);

            inlineShape.Width  = width;  // 图片宽度
            inlineShape.Height = height; // 图片高度
            Shape cShape = inlineShape.ConvertToShape();

            cShape.WrapFormat.Type = WdWrapType.wdWrapNone;
            oWordApplic.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; //居中显示图片
            InsertLineBreak();
            oWordApplic.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; //居中显示
            InsertText(hint);
            //oWordApplic.Selection.InlineShapes.AddPicture(picPath, ref missing, ref missing, ref missing);
        }
Example #6
0
        /// <summary>
        /// 插入表格
        /// </summary>
        /// <param name="n"></param>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <param name="value"></param>
        public void InsertCellImage(int n, int row, int column, string imgPath, string title, string description)
        {
            object missing = System.Reflection.Missing.Value;

            if (!System.IO.File.Exists(imgPath))
            {
                return;
            }
            object linkToFile       = false;
            object saveWithDocument = true;

            doc.Content.Tables[n].Cell(row, column).Select();

            app.Selection.TypeParagraph();//插入段落
            app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            app.Selection.Range.Font.Size = 13;
            app.Selection.TypeText(title);
            app.Selection.Range.Font.Size = 13;
            app.Selection.InsertParagraphAfter();

            object      range = app.Selection.Range;
            InlineShape shape = app.ActiveDocument.InlineShapes.AddPicture(imgPath, ref linkToFile, ref saveWithDocument, ref range);

            shape.ConvertToShape().WrapFormat.Type = WdWrapType.wdWrapTopBottom;
            app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

            object count  = 0;
            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行;

            app.Selection.MoveDown(ref WdLine, ref count, ref missing);   //移动焦点
            app.Selection.TypeParagraph();                                //插入段落
            app.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            app.Selection.Range.Font.Size = 11;
            app.Selection.TypeText(description);
            app.Selection.Range.Font.Size = 11;
            app.Selection.InsertParagraphAfter();
        }
Example #7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string imagePath  = @"C:\Temp\test.png";
            string docPath    = @"c:\temp\test.docx";
            string newDocPath = @"c:\temp\test-new.docx";

            Application wordApp = new Application();

            if (!File.Exists(docPath))
            {
                Console.WriteLine("Source Word document doesn't exist, please put a document in the path: " + docPath);
                return;
            }

            if (!File.Exists(imagePath))
            {
                Console.WriteLine("Image file doesn't exist, please put a document in the path: " + imagePath);
                return;
            }

            Document wordDoc = wordApp.Documents.Open(docPath);

            object saveWithDocument = true;
            object missing          = Type.Missing;

            // Get pages count
            WdStatistic PagesCountStat = WdStatistic.wdStatisticPages;
            int         PagesCount     = wordDoc.ComputeStatistics(PagesCountStat, ref missing);

            //Get pages
            object What  = WdGoToItem.wdGoToPage;
            object Which = 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 = wordApp.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref missing).Start;

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

                // Get text
                object oRange;
                if (Convert.ToInt32(Start.ToString()) != Convert.ToInt32(End.ToString()))
                {
                    //Pages.Add(wordDoc.Range(ref Start, ref End).Text);

                    oRange = wordDoc.Range(ref Start, ref End);
                }
                else
                {
                    //Pages.Add(wordDoc.Range(ref Start).Text);

                    oRange = wordDoc.Range(ref Start);
                }

                InlineShape pic = wordDoc.InlineShapes.AddPicture(imagePath, ref missing, ref saveWithDocument, ref oRange);
                pic.Width  = 595;
                pic.Height = 842;

                Shape shapePic = pic.ConvertToShape();
                shapePic.Left            = -50;
                shapePic.Top             = -30;
                shapePic.WrapFormat.Type = WdWrapType.wdWrapFront;
            }

            wordDoc.SaveAs2(newDocPath);
            wordApp.Quit();

            Console.WriteLine("Please check the new file: " + newDocPath);
        }
Example #8
0
        public static void CreateDocument(string FilePath, EStudent student)
        {
            try
            {
                Photo photo = new Photo();
                //Create an instance for word app
                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                Document wordDoc      = winword.Documents.Add();
                Range    range        = wordDoc.Range();
                int      fontStandart = 10;
                int      fontBig      = 11;
                int      fontSmall    = 8;
                int      fontHead     = 14;

                //Set animation status for word application
                // winword.ShowAnimation = true;

                //Set status for word application is to be visible or not.
                winword.Visible = false;

                //Create a missing variable for missing value
                object missing = System.Reflection.Missing.Value;

                //Create a new document
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);

                //Add header into the document
                foreach (Microsoft.Office.Interop.Word.Section section in document.Sections)
                {
                    //Get the header range and add the header details.
                    Microsoft.Office.Interop.Word.Range headerRange = section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    headerRange.Fields.Add(headerRange, Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage);
                    headerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    headerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlue;
                    headerRange.Font.Size = 10;
                    headerRange.Text      = "";
                }

                //Add the footers into the document
                foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
                {
                    //Get the footer range and add the footer details.
                    Microsoft.Office.Interop.Word.Range footerRange = wordSection.Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkRed;
                    footerRange.Font.Size                 = 10;
                    footerRange.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    footerRange.Text = "";
                }



                //adding text to document
                document.Content.SetRange(0, 0);
                //document.Content.Text = "ЗАТВЕРДЖЕНО" +
                //    "Наказ Міністерства освіти" +
                //    "і науки України" +
                //    "06.06.2017 № 794" + Environment.NewLine;


                Microsoft.Office.Interop.Word.Paragraph oPara2 = document.Content.Paragraphs.Add(ref missing);
                Range rng = oPara2.Range;
                rng.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseStart);
                InlineShape shape = document.InlineShapes.AddPicture(@"C:\Users\Arikatamo\Pictures\img8.jpg", ref missing, ref missing, rng);
                //InlineShape shape = document.InlineShapes.AddPicture(photo.ByteToImage(student.Image), ref missing, ref missing, rng);

                shape.Width  = 100;
                shape.Height = 100;
                rng          = shape.Range;
                Microsoft.Office.Interop.Word.Shape s2 = shape.ConvertToShape();
                oPara2.Format.SpaceAfter = 0;
                s2.WrapFormat.Type       = WdWrapType.wdWrapTight;

                //Add paragraph with Heading 1 style
                Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
                object styleHeading = "No Spacing";
                para1.Range.set_Style(ref styleHeading);
                // And paste it to the target Range
                string[] Parahraps = { "ЗАТВЕРДЖЕНО", "Наказ Міністерства освіти", "і науки України", "06.06.2017 № 794" };
                foreach (var item in Parahraps)
                {
                    para1.Range.Text = item;
                    para1.Range.set_Style(ref styleHeading);
                    para1.Range.Font.Size        = fontBig;
                    para1.Range.Font.Color       = WdColor.wdColorBlack;
                    para1.Format.SpaceAfter      = 5;
                    para1.Format.FirstLineIndent = 170;
                    para1.Range.InsertParagraphAfter();
                }
                string TempLine = "__________________________________________________________________________________________";
                int    MaxCount = TempLine.Length;
                Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                para2.Range.Text        = "Форма № Н - 1.01.2.3";
                para2.Range.Font.Size   = fontHead;
                para2.Range.Font.Color  = WdColor.wdColorBlack;
                para2.Range.Font.Bold   = 1;
                para2.Format.SpaceAfter = 10;
                para2.Alignment         = WdParagraphAlignment.wdAlignParagraphRight;
                para2.Range.InsertParagraphAfter();
                para2.Range.Font.Bold = 0;

                string[] Named = { student.Name, student.SName, student.FName };
                //Керівнику
                Microsoft.Office.Interop.Word.Paragraph Para1 = document.Content.Paragraphs.Add(ref missing);
                string temp = $"Керівнику:";
                Para1.Range.Text = temp;
                var ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.Alignment  = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.SpaceAfter = 0;
                // Назва Закладу
                Range rr = Para1.Range;
                rr.Start     = ll;
                rr.Text      = $"\t{Named[0]}  {Named[1]}  {Named[2]}";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                Para1.Range.InsertParagraphAfter();
                /// (найменування вищого навчального закладу)
                Para1.Range.Text      = "(найменування вищого навчального закладу)";
                Para1.Range.Font.Size = fontSmall;
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //вступника
                temp             = $"Вступника:";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                // Вступник
                rr           = Para1.Range;
                rr.Start     = ll;
                rr.Text      = $"\t{Named[0]}  {Named[1]}  {Named[2]}";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                Para1.Range.InsertParagraphAfter();
                /// (прізвище, ім&#39;я та по батькові)
                Para1.Range.Text      = "(прізвище, ім&#39;я та по батькові)";
                Para1.Range.Font.Size = fontSmall;
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                // Заява
                Para1.Range.Text = "Заява";
                styleHeading     = "Title";
                Para1.Range.set_Style(ref styleHeading);
                Para1.SpaceAfter       = 1;
                Para1.SpaceBefore      = 3;
                Para1.Range.Font.Size  = fontHead;
                Para1.Range.Font.Bold  = 1;
                Para1.Range.Font.Color = WdColor.wdColorBlack;
                Para1.Alignment        = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                // Прошу допустити мене до участі в конкурсному відборі на навчання:
                Para1.Range.Text             = "Прошу допустити мене до участі в конкурсному відборі на навчання:";
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 1;
                Para1.Range.InsertParagraphAfter();
                //форма навчання
                temp             = $"форма навчання:";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                // Форма
                int rangeDays;

                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $"\t{student.FormEdu.Name}\t,";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;

                // освітньо-кваліфікаційний рівень молодший спеціаліст,
                rr           = Para1.Range;
                rr.Start     = ll;
                rr.Text      = $"\tосвітньо - кваліфікаційний рівень молодший спеціаліст,";
                rr.Font.Bold = 0;
                rr.Font.Size = fontStandart;
                Para1.Range.InsertParagraphAfter();

                /// (денна, заочна (дистанційна), вечірня)
                Para1.Range.Text      = "\t\t(денна, заочна (дистанційна), вечірня)";
                Para1.Range.Font.Size = fontSmall;
                Para1.Range.Font.Bold = 0;
                Para1.SpaceAfter      = 1;
                Para1.Range.InsertParagraphAfter();
                /// конкурсна пропозиція
                temp             = $"конкурсна пропозиція:";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Сама пропозиція
                var NamedPropos = "Конкурсна Пропозиція";
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $"\t{NamedPropos}\t";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                /// (назва конкурсної пропозиції державною мовою)
                Para1.Range.Text      = "(назва конкурсної пропозиції державною мовою)";
                Para1.Range.Font.Size = fontSmall;
                Para1.SpaceAfter      = 1;
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //спеціальність
                temp             = $"спеціальність:";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Сама Спеціальність
                NamedPropos  = "Програміст";
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $"\t{NamedPropos}\t";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //(код та найменування спеціальності, спеціалізації спеціальностей 014, 015, 035, 275)
                Para1.Range.Text      = "(код та найменування спеціальності, спеціалізації спеціальностей 014, 015, 035, 275)";
                Para1.Range.Font.Size = fontSmall;
                Para1.SpaceAfter      = 1;
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                // назва спеціалізацій, освітніх програм, нозологій, мов, музичних інструментів тощо в межах спеціальності
                string[] tem  = { "First", "Second", "Third" };
                string   text = "";
                for (int i = 0; i < tem.Length; i++)
                {
                    text += tem[i];
                    if (i < tem.Length - 1)
                    {
                        text += " , ";
                    }
                }
                Para1.Range.Text      = text;
                Para1.Range.Font.Size = fontBig;
                Para1.Range.Font.Bold = 1;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //(назва спеціалізацій, освітніх програм, нозологій, мов, музичних інструментів тощо в межах спеціальності)
                Para1.Range.Text      = "(назва спеціалізацій, освітніх програм, нозологій, мов, музичних інструментів тощо в межах спеціальності)";
                Para1.Range.Font.Size = fontSmall;
                Para1.SpaceAfter      = 1;
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //на основі освітньо-кваліфікаційного рівня
                temp             = $"на основі освітньо-кваліфікаційного рівня:";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                // Кваліфікаційний рівень
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $"\t{student.CvalLvl.Name}\t";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //(кваліфікований робітник, молодший спеціаліст)
                Para1.Range.Text             = "(кваліфікований робітник, молодший спеціаліст)";
                Para1.Range.Font.Size        = fontSmall;
                Para1.Format.FirstLineIndent = 80;
                Para1.SpaceAfter             = 1;
                Para1.Range.Font.Bold        = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //Претендую на участь у конкурсі на місця державного та регіонального замовлення і на участь у конкурсі на
                // місця за кошти фізичних та юридичних осіб у випадку неотримання рекомендації за цією конкурсною пропозицією
                // за державним або регіональним замовленням.
                temp = $"Претендую на участь у конкурсі на місця державного та регіонального замовлення і на участь у конкурсі на" +
                       $"місця за кошти фізичних та юридичних осіб у випадку неотримання рекомендації за цією конкурсною пропозицією" +
                       $"за державним або регіональним замовленням.";
                Para1.Range.Text             = temp;
                Para1.Format.FirstLineIndent = 40f;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();
                // Претендую на участь у конкурсі виключно на місця державного та регіонального замовлення.
                Para1.Range.Text      = "Претендую на участь у конкурсі виключно на місця державного та регіонального замовлення.";
                Para1.Range.Font.Size = fontBig;
                Para1.SpaceAfter      = 2;
                Para1.SpaceBefore     = 10;
                if (student.CatZarah.Name == "Державна")
                {
                    Para1.Range.Font.Underline = WdUnderline.wdUnderlineSingle;
                }
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                Para1.Range.Font.Underline = WdUnderline.wdUnderlineNone;
                // Претендую на участь у конкурсі виключно на місця за кошти фізичних та юридичних осіб.
                Para1.Range.Text      = "Претендую на участь у конкурсі виключно на місця за кошти фізичних та юридичних осіб.";
                Para1.Range.Font.Size = fontBig;
                Para1.SpaceAfter      = 2;
                Para1.SpaceBefore     = 10;
                if (student.CatZarah.Name == "Приватна")
                {
                    Para1.Range.Font.Underline = WdUnderline.wdUnderlineSingle;
                }
                Para1.Range.Font.Bold = 0;
                Para1.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                Para1.Range.Font.Underline = WdUnderline.wdUnderlineNone;

                //Про себе повідомляю

                Para1.Range.Text = "Про себе повідомляю";
                styleHeading     = "Title";
                Para1.Range.set_Style(ref styleHeading);
                Para1.SpaceAfter       = 1;
                Para1.SpaceBefore      = 3;
                Para1.Range.Font.Size  = fontHead;
                Para1.Range.Font.Bold  = 1;
                Para1.Range.Font.Color = WdColor.wdColorBlack;
                Para1.Alignment        = WdParagraphAlignment.wdAlignParagraphCenter;
                Para1.Range.InsertParagraphAfter();
                //Освітньо-кваліфікаційний рівень молодшого спеціаліста за кошти державного бюджету:
                temp             = $"Освітньо-кваліфікаційний рівень молодшого спеціаліста за кошти державного бюджету: ніколи не здобувався - ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Так
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" Так ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //вже здобутий раніше -
                temp             = $"вже здобутий раніше - ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Ні
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" Ні ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //вже здобувався раніше (навчання не завершено) -
                temp             = $"вже здобувався раніше (навчання не завершено) - ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Так
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" Так ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //Закінчив(ла)
                temp             = $"Закінчив(ла): ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //"Тут має бути текст про закінчення закладу!"
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" Тут має бути текст про закінчення закладу! ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //Іноземна мова, яку вивчав(ла)
                temp             = $"Іноземна мова, яку вивчав(ла): ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Мова
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" Англійська ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();
                //Закінчив(ла)
                temp             = $"Середній бал диплома: ";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                //Оцінка
                rr           = Para1.Range;
                rr.Start     = ll;
                rangeDays    = rr.Start;
                rr.Text      = $" 10 ;";
                rr.Font.Size = fontBig;
                rr.Font.Bold = 1;
                ll           = Para1.Range.End;
                Para1.Range.InsertParagraphAfter();


                //На час навчання поселення в гуртожиток: потребую - ; не потребую - (можна добавити до студента змінну яка тут буде підставлятися)
                temp             = $"На час навчання поселення в гуртожиток: потребую - Так; не потребую - Ні";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();
                //Громадянство: Україна -; інша країна:
                temp             = $"Громадянство: Україна - Так; інша країна: Ні";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();
                //Стать: чоловіча - ; жіноча -
                string Man   = (student.Sex.Sex == "Чоловік") ? "Так" : "Ні";
                string Woman = (student.Sex.Sex == "Жінка") ? "Так" : "Ні";

                temp             = $"Стать: чоловіча - {Man}; жіноча - {Woman}";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();
                //Дата і місце народження:
                temp             = $"Дата і місце народження: {student.Residence.Oblast}, {student.Residence.Rajon}, {student.Residence.Town}";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();
                //Місце проживання: індекс__________, область ________________________, район_____________________________,
                //місто / смт / село ___________________________, вулиця__________________________, будинок ___, квартира ______,
                //домашній, мобільний телефони _________________________________, електронна пошта __________________________
                temp = $"Місце проживання: індекс: {student.Residence.Index}, область: {student.Residence.Oblast} , район: {student.Residence.Rajon}, " +
                       $"місто / смт / село: {student.Residence.Town}, вулиця: {student.Residence.Street}, будинок: {student.Residence.NumberBuild}, квартира: {student.Residence.NumberKW}," +
                       $"домашній, мобільний телефони: {student.Phone}, {student.MobilePhone}, електронна пошта: {student.Email}";
                Para1.Range.Text = temp;
                ll = Para1.Range.End;
                Para1.Format.FirstLineIndent = 0;
                Para1.Range.Font.Size        = fontStandart;
                Para1.Range.Font.Color       = WdColor.wdColorBlack;
                Para1.SpaceAfter             = 0;
                Para1.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                Para1.Range.InsertParagraphAfter();

                ////Add paragraph with Heading 2 style
                //Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
                //object styleHeading2 = "Heading 2";
                //para2.Range.set_Style(ref styleHeading2);
                //para2.Range.Text = "ВІДОМІСТЬ ВСТУПНОГО ВИПРОБУВАННЯ";
                //para2.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;

                //para2.Range.InsertParagraphAfter();


                //Create a 5X5 table and insert some dummy record
                //Table firstTable = document.Tables.Add(para1.Range, 5, 5, ref missing, ref missing);

                //firstTable.Borders.Enable = 1;
                //foreach (Row row in firstTable.Rows)
                //{
                //    foreach (Cell cell in row.Cells)
                //    {
                //        //Header row
                //        if (cell.RowIndex == 1)
                //        {
                //            cell.Range.Text = "Column " + cell.ColumnIndex.ToString();
                //            cell.Range.Font.Bold = 1;
                //            //other format properties goes here
                //            cell.Range.Font.Name = "verdana";
                //            cell.Range.Font.Size = 10;
                //            //cell.Range.Font.ColorIndex = WdColorIndex.wdGray25;
                //            cell.Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                //            //Center alignment for the Header cells
                //            cell.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                //            cell.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;

                //        }
                //        //Data row
                //        else
                //        {
                //            cell.Range.Text = (cell.RowIndex - 2 + cell.ColumnIndex).ToString();
                //        }
                //    }
                //}

                //Save the document
                object filename = FilePath + @"\Форма_№_Н_1.01.2.3_" + student.Name + "_.docx";
                document.SaveAs2(ref filename);
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;
                //throw new Exception("Documet Created");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private void IncrustingImage(string routeFile, List <Archive> ImageRoutes, string RoutePDF, List <Int32> ListDeleteTables)
        {
            object oMissing = System.Reflection.Missing.Value;

            object outputFile = (object)routeFile;

            Application wordApp = new Application();
            Document    doc     = wordApp.Documents.Open(ref outputFile, ref oMissing,
                                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            try {
                doc.Activate();


                var rangText = doc.Content;
                if (rangText.Find.Execute("Unlicensed version. Please register @ templater.info"))
                {
                    rangText.Expand(Microsoft.Office.Interop.Word.WdUnits.wdParagraph);
                    rangText.Delete();
                }
                object matchCase         = false;
                object matchWholeWord    = true;
                object matchWildCards    = false;
                object matchSoundsLike   = false;
                object matchAllWordForms = false;
                object forward           = true;
                object format            = false;
                object matchKashida      = false;
                object matchDiacritics   = false;
                object matchAlefHamza    = false;
                object matchControl      = false;
                object read_only         = false;
                object visible           = true;
                object replace           = 2;
                object wrap = 1;

                //execute find and replace
                ReplaceTextFormat("True", "SI", ref wordApp);
                ReplaceTextFormat("False", "NO", ref wordApp);

                TextFormat("[[Medio]]", ref wordApp, WdColor.wdColorYellow);
                ReplaceTextFormat("[[Medio]]", "Medio", ref wordApp);

                TextFormat("[[Alto]]", ref wordApp, WdColor.wdColorRed);
                ReplaceTextFormat("[[Alto]]", "Alto", ref wordApp);

                TextFormat("[[Bajo]]", ref wordApp, WdColor.wdColorGreen);
                ReplaceTextFormat("[[Bajo]]", "Bajo", ref wordApp);

                TextFormat("[[Baixo]]", ref wordApp, WdColor.wdColorGreen);
                ReplaceTextFormat("[[Baixo]]", "Baixo", ref wordApp);
                //Replace Masculino
                //ReplaceTextFormat("[[Data.oBasicInformation_BrasilVm.Sexo]]", "Alto", ref wordApp);


                int contador = 1;

                foreach (Microsoft.Office.Interop.Word.Table tbl in doc.Tables)
                {
                    if (ListDeleteTables.Contains(contador))
                    {
                        tbl.Delete();
                    }
                    contador++;
                }


                foreach (var image in ImageRoutes.Where(x => x.typeAdjunte == TypeAdjunte.image))
                {
                    Find fnd = wordApp.ActiveWindow.Selection.Find;
                    fnd.ClearFormatting();
                    fnd.Replacement.ClearFormatting();
                    fnd.Forward = true;
                    fnd.Wrap    = WdFindWrap.wdFindContinue;

                    string imagePath = image.RutaArchivo;
                    var    keyword   = "[[" + image.NameTypeFile + "]]";
                    var    sel       = wordApp.Selection;
                    // = string.Format("{{0}}", keyword);
                    sel.Find.Text = keyword;
                    wordApp.Selection.Find.Execute(keyword);
                    Range range = wordApp.Selection.Range;
                    if (range.Text != null && range.Text.Contains(keyword))
                    {
                        Range temprange = doc.Range(range.End - keyword.Length, range.End);  //keyword is of 4 charecter range.End - 4
                        temprange.Select();
                        Selection currentSelection = wordApp.Selection;
                        sel.Find.Execute(Replace: WdReplace.wdReplaceOne);
                        sel.Range.Select();
                        var         imagePath1 = Path.GetFullPath(string.Format(imagePath, keyword));
                        InlineShape shape      = sel.InlineShapes.AddPicture(FileName: imagePath1, LinkToFile: false, SaveWithDocument: true);
                        Shape       sh         = shape.ConvertToShape();
                        sh.Width  = image.widthImage;
                        sh.Height = image.HeightImage;
                        //shape.ConvertToShape();
                        sh.WrapFormat.Type = WdWrapType.wdWrapSquare;
                        sh.Top             = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
                        sh.Left            = (float)Microsoft.Office.Interop.Word.WdShapePosition.wdShapeCenter;
                    }
                }

                string[] ListRetir = new string[] { "FotoGrafico", "Firma", "FotoEntradaDomicilio", "FotoAmbienteSocial", "FotoHabitaciones", "FotoCocina" };


                foreach (string i in ListRetir)
                {
                    int exist = ImageRoutes.Where(x => x.NameTypeFile == i).Count();
                    if (exist == 0)
                    {
                        ReplaceTextFormat("[[" + i + "]]", "", ref wordApp);
                    }
                }



                object outputFileName = RoutePDF;
                object fileFormat     = WdSaveFormat.wdFormatPDF;

                doc.SaveAs(ref outputFileName,
                           ref fileFormat, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                           ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
            }
            catch (Exception ex)
            {
                throw ex;
                //Elog.Save(ex.message);
            }
            finally
            {
                if (doc != null)
                {
                    ((_Document)doc).Close(ref oMissing, ref oMissing, ref oMissing);
                    Marshal.FinalReleaseComObject(doc);
                }
                if (wordApp != null)
                {
                    ((_Application)wordApp).Quit();
                    Marshal.FinalReleaseComObject(wordApp);
                }
            }
        }
        private void ImprimeDatosFuncionarios(Range rng, DataRow[] funcionarios)
        {
            Object oMissing = System.Reflection.Missing.Value;
            int inicio = rng.Start;
            for (int i = 0; i < funcionarios.Length; i++)
            {
                float PageWidthPoints = Globals.ThisAddIn.Application.ActiveDocument.PageSetup.PageWidth;
                string nombre = funcionarios[i]["PrimerNombre"] + " " + funcionarios[i]["SegundoNombre"] + " " + funcionarios[i]["ApellidoPaterno"] + " " + funcionarios[i]["ApellidoMaterno"];
                WriteLine(rng, nombre, (float)16, Italic.NoItalicas, "Century Gothic", Formato.Centrado, Bold.Bold, ALaLinea.NewLine);
                DataRow[] puestos = Datos.Instance.GetPuestos(funcionarios[i]["ID"].ToString());
                if (puestos.Length > 0)
                {
                    bool YaImprimiDependencia = false;
                    //WriteLine(rng, puestos[puestos.Length - 1]["Puesto"].ToString(), (float)10.5, Italic.NoItalicas, "Century Gothic", Formato.Centrado, Bold.NoBold, ALaLinea.NewLine);
                    for (int k = 0; k < puestos.Length; k++)
                    {
                        if (puestos[k]["CargoActual"].ToString().Equals("actual"))
                        {
                            WriteLine(rng, puestos[k]["DependenciaEntidad"].ToString(), (float)10.5, Italic.NoItalicas, "Century Gothic", Formato.Centrado, Bold.NoBold, ALaLinea.NewLine);
                            YaImprimiDependencia = true;
                        }
                    }
                    if (!YaImprimiDependencia)
                    {
                        WriteLine(rng, puestos[0]["DependenciaEntidad"].ToString(), (float)10.5, Italic.NoItalicas, "Century Gothic", Formato.Centrado, Bold.NoBold, ALaLinea.NewLine);
                    }
                }

                /* Poner la foto aquí */
                WriteLine(rng, "\n", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                string FullName = Datos.Instance.GetFoto(funcionarios[i]["ID"].ToString());
                if (FullName != String.Empty)
                {
                    object PhotoPos = rng;

                    ((Range) PhotoPos).Paragraphs.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    object tr = true;
                    object fa = true;
                    InlineShape shape = Globals.ThisAddIn.Application.ActiveDocument.InlineShapes.AddPicture(FullName, ref tr, ref fa, ref PhotoPos);
                    
                    float alto = shape.Height;
                    float ancho = shape.Width;
                    float anchoDoc = Globals.ThisAddIn.Application.ActiveDocument.PageSetup.PageWidth;
                    float AnchoUtilizable = anchoDoc - Globals.ThisAddIn.Application.ActiveDocument.PageSetup.LeftMargin - Globals.ThisAddIn.Application.ActiveDocument.PageSetup.RightMargin;
                    shape.Width = (float)0.25 * AnchoUtilizable;
                    shape.Height = (alto / ancho) * (float)0.25 * AnchoUtilizable;
                    Shape ShapeFoto = shape.ConvertToShape();
                    InlineShape shape1 = Globals.ThisAddIn.Application.ActiveDocument.InlineShapes.AddPicture(FullName, ref tr, ref fa, ref PhotoPos);
                    shape1.Height = (alto / ancho) * (float)0.25 * AnchoUtilizable;
                    shape1.Width = 0;
                    ShapeFoto.Left = (float)(0.75 / 2.0) * (anchoDoc - Globals.ThisAddIn.Application.ActiveDocument.PageSetup.LeftMargin - Globals.ThisAddIn.Application.ActiveDocument.PageSetup.RightMargin);
                    Range rangoFoto = shape.Range;
                    rangoFoto.Collapse(WdCollapseDirection.wdCollapseEnd);
                    rangoFoto.Select();
                    rng = rangoFoto;
                    rng.Collapse(WdCollapseDirection.wdCollapseEnd);
                    rng.Select();
                    FileInfo fi = new FileInfo(FullName);
                    if (fi.Exists) File.Delete(FullName);
                    //WriteLine(rng, "\n" + alto.ToString() + " " + ancho.ToString() + " " + anchoDoc.ToString(), (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NewLine);
                }

                WriteLine(rng, "\n", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NewLine);

                Table tabla1 = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(rng, 5, 2);

                tabla1.AllowPageBreaks = true;
                tabla1.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                tabla1.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

                tabla1.PreferredWidth = PageWidthPoints;
                tabla1.Columns[1].SetWidth(PageWidthPoints * (float) (0.15), WdRulerStyle.wdAdjustSameWidth);

                //tabla1.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                //WriteLine(tabla1.Cell(1, 1).Range, "Nombre Completo", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                //string nombreCompleto = funcionarios[i]["PrimerNombre"] + " " + funcionarios[i]["SegundoNombre"] + " " + funcionarios[i]["ApellidoPaterno"] + " " + funcionarios[i]["ApellidoMaterno"];
                //WriteLine(tabla1.Cell(1, 2).Range, nombreCompleto, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                tabla1.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                WriteLine(tabla1.Cell(1, 1).Range, "Fecha de nacimiento", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                WriteLine(tabla1.Cell(1, 2).Range,
                    Fecha.FechaString(funcionarios[i]["AñoNacimiento"].ToString().Replace("\n", string.Empty),
                        funcionarios[i]["MesNacimiento"].ToString().Replace("\n", string.Empty),
                        funcionarios[i]["DiaNacimiento"].ToString().Replace("\n", string.Empty), " "),
                    (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                //         Adscripción Política
                tabla1.Cell(2, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                WriteLine(tabla1.Cell(2, 1).Range, "Partido", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                string nombrefuncionario = funcionarios[i]["ID"].ToString();
                DataRow[] adscripcionPolitica = Datos.Instance.GetAdscripcionPolitica(nombrefuncionario);
                string HistoriaPartidista = "";
                for (int j = 0; j < adscripcionPolitica.Length; j++)
                {
                    if (!adscripcionPolitica[j]["NombreDelPartido"].ToString().Equals("No Disponible"))
                    {
                        HistoriaPartidista += adscripcionPolitica[j]["NombreDelPartido"].ToString().Replace("\n", string.Empty) + " ";
                        if (!adscripcionPolitica[j]["FechaDeInicio"].ToString().Equals("1900") &
                            !adscripcionPolitica[j]["FechaDeInicio"].ToString().Equals("") &
                            !adscripcionPolitica[j]["FechaDeFin"].ToString().Equals("1900") &
                            !adscripcionPolitica[j]["FechaDeFin"].ToString().Equals(""))
                        {
                            HistoriaPartidista += adscripcionPolitica[j]["FechaDeInicio"].ToString().Replace("\n", string.Empty) + " a " +
                                adscripcionPolitica[j]["FechaDeFin"].ToString().Replace("\n", string.Empty) + "\n\n";
                        }   
                        //HistoriaPartidista += (j == 0) ? string.Empty : "\n";
                    }
                }
                //tabla1.Cell(2, 2).Range.ListFormat.ApplyNumberDefault(ref oMissing);
                //ListTemplate lt1 = tabla1.Cell(2, 2).Range.ListFormat.ListTemplate;
                //tabla1.Cell(2, 2).Range.ListFormat.ApplyListTemplate(lt1, false);

                WriteLine(tabla1.Cell(2, 2).Range, HistoriaPartidista, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NewLine);

                //      Cargo Actual
                tabla1.Cell(3, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                WriteLine(tabla1.Cell(3, 1).Range, "Cargo Actual", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                WriteLine(tabla1.Cell(3, 2).Range, PuestoActual(puestos).Replace("\n", string.Empty) + "\n", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NewLine);

                //     Datos de Contacto
                tabla1.Cell(4, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                WriteLine(tabla1.Cell(4, 1).Range, "Datos de Contacto", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                DataRow[] DatosContacto = Datos.Instance.GetDatosContacto(funcionarios[i]["ID"].ToString());
                string StringDatosContacto = "";
                for (int j = 0; j < DatosContacto.Length; j++)
                {
                    StringDatosContacto += DatosContacto[j]["Tipo"].ToString().Replace("\n", string.Empty) + ": " +
                        DatosContacto[j]["dato"].ToString().Replace("\n", string.Empty) + "\n\n";
                    //StringDatosContacto += (DatosContacto.Length > 1) ? "\n" : string.Empty;
                }
                //if (DatosContacto.Length > 1)
                //{
                //    StringDatosContacto = StringDatosContacto.Remove(StringDatosContacto.Length - 1);
                //}
                if (DatosContacto.Length > 0 )
                {
                    //tabla1.Cell(4, 2).Range.ListFormat.ApplyNumberDefault(ref oMissing);
                    //ListTemplate lt2 = tabla1.Cell(4, 2).Range.ListFormat.ListTemplate;
                    //tabla1.Cell(4, 2).Range.ListFormat.ApplyListTemplate(lt2, false);
                    WriteLine(tabla1.Cell(4, 2).Range, StringDatosContacto, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                }
                   

                //tabla1.Cell(4, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                //WriteLine(tabla1.Cell(4, 1).Range, "Datos de Contacto", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                //WriteLine(tabla1.Cell(4, 2).Range, "", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                //     Circulo Cercano
                tabla1.Cell(5, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                WriteLine(tabla1.Cell(5, 1).Range, "Circulo Cercano", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                DataRow[] CirculoCercano = Datos.Instance.GetCirculoCercano(funcionarios[i]["ID"].ToString());
                string StringCirculoCercano = "";
                for (int j = 0; j < CirculoCercano.Length; j++)
                {
                    StringCirculoCercano += CirculoCercano [j]["Nombre"].ToString().Replace("\n", string.Empty) + ": " +
                        CirculoCercano[j]["Información"].ToString().Replace("\n", string.Empty) + "\n\n";
                    //StringCirculoCercano += (j == 0) ? string.Empty : "\n";
                }
                if (CirculoCercano.Length > 0)
                {
                    //tabla1.Cell(5, 2).Range.ListFormat.ApplyNumberDefault(ref oMissing);
                    //ListTemplate lt3 = tabla1.Cell(5, 2).Range.ListFormat.ListTemplate;
                    //tabla1.Cell(5, 2).Range.ListFormat.ApplyListTemplate(lt3, false);
                    WriteLine(tabla1.Cell(5, 2).Range, StringCirculoCercano, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                }
                    
                //tabla1.Cell(5, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                //WriteLine(tabla1.Cell(5, 1).Range, "Circulo Cercano", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                //WriteLine(tabla1.Cell(5, 2).Range, "", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                rng = Globals.ThisAddIn.Application.ActiveDocument.Range(Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1, Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1);

                DataRow[] escolaridad = Datos.Instance.GetEscolaridad(funcionarios[i]["ID"].ToString());
                if (escolaridad.Length > 0)
                {
                    rng.Select();

                    WriteLine(rng, " ", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    Table tabla2 = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(rng, 1, 2);

                    tabla2.AllowPageBreaks = true;
                    tabla2.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                    tabla2.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

                    tabla2.PreferredWidth = PageWidthPoints;
                    tabla2.Columns[1].SetWidth(PageWidthPoints * (float)(0.15), WdRulerStyle.wdAdjustSameWidth);

                    tabla2.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                    WriteLine(tabla2.Cell(1, 1).Range, "Estudios", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    string datosEscolares = "";
                    for (int j = 0; j < escolaridad.Length; j++)
                    {
                        datosEscolares += escolaridad[j]["Universidad"].ToString().Replace("\n", string.Empty) + "  " + escolaridad[j]["Grado"].ToString().Replace("\n", string.Empty) + " - " + 
                            Fecha.FechaString(escolaridad[j]["AñoFinal"].ToString().Replace("\n", string.Empty),
                                escolaridad[j]["MesFinal"].ToString().Replace("\n", string.Empty),
                                escolaridad[j]["DiaFinal"].ToString().Replace("\n", string.Empty), " ") + "\n\n";
                        //datosEscolares += (j == escolaridad.Length - 1) ? string.Empty : "\n";
                    }
                    //tabla2.Cell(1, 2).Range.ListFormat.ApplyBulletDefault(ref oMissing);
                    WriteLine(tabla2.Cell(1, 2).Range, datosEscolares, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                    rng = Globals.ThisAddIn.Application.ActiveDocument.Range(Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1, Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1);
                }

                if (puestos.Length > 0)
                {
                    rng.Select();

                    WriteLine(rng, " ", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    Table tabla3 = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(rng, 1, 2);

                    tabla3.AllowPageBreaks = true;
                    tabla3.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                    tabla3.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

                    tabla3.PreferredWidth = PageWidthPoints;
                    tabla3.Columns[1].SetWidth(PageWidthPoints * (float)(0.20), WdRulerStyle.wdAdjustSameWidth);

                    tabla3.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                    WriteLine(tabla3.Cell(1, 1).Range, "Trayectoria", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                    string trayectoria = "";
                    for (int j = 0; j < puestos.Length; j++)
                    {
                        if (!puestos[j]["CargoActual"].ToString().Equals("actual"))
                        {
                            trayectoria += puestos[j]["Puesto"].ToString().Replace("\n", string.Empty) + " - " + puestos[j]["DependenciaEntidad"].ToString().Replace("\n", string.Empty) + " - " +
                            Fecha.FechaString(puestos[j]["AñoInicial"].ToString().Replace("\n", string.Empty),
                                puestos[j]["MesInicial"].ToString().Replace("\n", string.Empty),
                                puestos[j]["DiaInicial"].ToString().Replace("\n", string.Empty), string.Empty) + "   " +
                            Fecha.FechaString(puestos[j]["AñoFinal"].ToString().Replace("\n", string.Empty),
                                puestos[j]["MesFinal"].ToString().Replace("\n", string.Empty),
                                puestos[j]["DiaFinal"].ToString().Replace("\n", string.Empty), " ") + "\n\n";
                            //trayectoria += (j == puestos.Length - 1) ? string.Empty : "\n";
                        }
                    }
                    //tabla3.Cell(1, 2).Range.ListFormat.ApplyBulletDefault(ref oMissing);
                    WriteLine(tabla3.Cell(1, 2).Range, trayectoria, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                    rng = Globals.ThisAddIn.Application.ActiveDocument.Range(Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1, Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1);
                }

                DataRow[] notas = Datos.Instance.GetNotasRelevantes(funcionarios[i]["ID"].ToString());
                if (notas.Length > 0)
                {
                    rng.Select();

                    WriteLine(rng, " ", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    Table tabla4 = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(rng, 1, 2);

                    tabla4.AllowPageBreaks = true;
                    tabla4.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                    tabla4.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

                    tabla4.PreferredWidth = PageWidthPoints;
                    tabla4.Columns[1].SetWidth(PageWidthPoints * (float)(0.20), WdRulerStyle.wdAdjustSameWidth);

                    tabla4.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                    WriteLine(tabla4.Cell(1, 1).Range, "Notas relevantes", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    string notasRelevantes = "";
                    for (int j = 0; j < notas.Length; j++)
                    {
                        notasRelevantes += notas[j]["Referencia"].ToString().Replace("\n\n", "\n") + "\n\n";
                        //notasRelevantes += (j == notas.Length - 1) ? string.Empty : "\n";
                    }
                    //tabla4.Cell(1, 2).Range.ListFormat.ApplyNumberDefault(ref oMissing);
                    //ListTemplate lt = tabla4.Cell(1, 2).Range.ListFormat.ListTemplate;
                    //tabla4.Cell(1, 2).Range.ListFormat.ApplyListTemplate(lt , false);
                    WriteLine(tabla4.Cell(1, 2).Range, notasRelevantes, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    rng = Globals.ThisAddIn.Application.ActiveDocument.Range(Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1, Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1);
                }

                DataRow[] comentarios = Datos.Instance.GetComentarios(funcionarios[i]["ID"].ToString());
                if (comentarios.Length > 0)
                {
                    rng.Select();

                    WriteLine(rng, " ", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    Table tabla5 = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(rng, 1, 2);

                    tabla5.AllowPageBreaks = true;
                    tabla5.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                    tabla5.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

                    tabla5.PreferredWidth = PageWidthPoints;
                    tabla5.Columns[1].SetWidth(PageWidthPoints * (float)(0.20), WdRulerStyle.wdAdjustSameWidth);

                    tabla5.Cell(1, 1).Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)Defines.ColorInstitucional;
                    WriteLine(tabla5.Cell(1, 1).Range, "Comentarios", (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);

                    string comments = "";
                    for (int j = 0; j < comentarios.Length; j++)
                    {
                        comments += comentarios[j]["Referencia"].ToString().Replace("\n\n", "\n");
                        comments += (j == comentarios.Length - 1) ? string.Empty : "\n";
                    }
                    //tabla5.Cell(1, 2).Range.ListFormat.ApplyBulletDefault(ref oMissing);
                    WriteLine(tabla5.Cell(1, 2).Range, comments, (float)10, Italic.NoItalicas, "Century Gothic", Formato.Justificado, Bold.NoBold, ALaLinea.NoNewLine);
                    rng = Globals.ThisAddIn.Application.ActiveDocument.Range(Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1, Globals.ThisAddIn.Application.ActiveDocument.Content.End - 1);
                }

                // insertamos un salto de pagina al final de los datos de cada funcionario
                //Utility.InsertText(currentSelection, "==========================================================");
                object type = 7;
                rng.InsertBreak(ref type);
                int fin = rng.End;
                Range rango = Globals.ThisAddIn.Application.ActiveDocument.Range(inicio, fin);
                rango.Paragraphs.Space1();
                rango.Paragraphs.SpaceBefore = 0;
                rango.Paragraphs.SpaceAfter = 0;

                rng.Collapse(WdCollapseDirection.wdCollapseEnd);
                rng.Select();
                
            }
        }
Example #11
0
        // METHOD - Create the Word doc
        private void CreateWordDoc(DataGridView DGV)
        {
            if (DGV.Rows.Count != 0)
            {
                //Create a missing variable for missing value
                object oMissing = Missing.Value;
                // \endofdoc is a predefined bookmark
                object oEndOfDoc = "\\endofdoc";

                //Start Word and create a new document.
                _Application oWord = new Word.Application();
                oWord.Visible = true;
                _Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing);

                int RowCount = DGV.Rows.Count;

                // Iterate over each DataGrid row and extract image path and caption text
                for (int i = 0; i <= RowCount - 1; i++)
                {
                    // make a para as numbered list
                    Paragraph oPara0 = oDoc.Content.Paragraphs.Add(ref oMissing);
                    oPara0.KeepWithNext      = 0;
                    oPara0.Format.SpaceAfter = 0;
                    Paragraph oPara1     = oDoc.Content.Paragraphs.Add(ref oMissing);
                    Range     rngTarget0 = oPara0.Range;
                    Range     rngTarget1 = oPara1.Range;
                    rngTarget0.Font.Size = 12;
                    rngTarget0.Font.Name = "Tahoma";
                    rngTarget1.Font.Size = 12;
                    rngTarget1.Font.Name = "Tahoma";
                    object anchor = rngTarget1;

                    //oPara.Range.ListFormat.ApplyNumberDefault();
                    rngTarget0.ListFormat.ApplyNumberDefault();


                    // Get image path and caption from dataGridView
                    string fileName1 = DGV.Rows[i].Cells[2].Value.ToString();
                    string caption   = DGV.Rows[i].Cells[1].Value.ToString();


                    InlineShape pic = rngTarget1.InlineShapes.AddPicture(fileName1, ref oMissing, ref oMissing, ref anchor);

                    Shape sh = pic.ConvertToShape();
                    sh.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoCTrue;

                    // Windows runs as default at 96dpi (display) Macs run as default at 72 dpi (display)
                    // Assuming 72 points per inch
                    // 3.5 inches is 3.5*72 = 252
                    // 3.25 inches is 3.25*72 = 234

                    sh.Height = 252;

                    if (sh.Width > 400)
                    {
                        sh.Width = 400;
                    }

                    sh.Left = (float)WdShapePosition.wdShapeCenter;
                    sh.Top  = 0;

                    //Write substring into Word doc with a bullet before it.
                    rngTarget0.InsertBefore(caption + "\v");
                    oPara1.Format.SpaceAfter = 264;
                    //rngTarget1.InsertParagraphAfter();
                }
            }
        }