Ejemplo n.º 1
0
        public void AddToc()
        {
            wordApp = new Application();
            object file = filePath;

            try
            {

                wordDocument = wordApp.Documents.Open(ref file, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing, ref paramMissing, ref paramMissing,
                                    ref paramMissing
                );

                Range tocRange = wordDocument.Range(0, 0);
                TableOfContents toc = wordDocument.TablesOfContents.Add(tocRange, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);
                toc.Update();

                int end = toc.Range.End;
                Range tocEnd = wordDocument.Range(end, end);

                tocEnd.InsertParagraphBefore();
                tocEnd.InsertBreak(WdBreakType.wdPageBreak);

            }
            catch (COMException ex)
            {
                throw new InvalidOperationException("Invalid Document", ex);
            }
            finally {
                Dispose();
            }
        }
Ejemplo n.º 2
0
        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);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// An inline rich text control can't contain carriage returns.
        /// </summary>
        /// <param name="control"></param>
        public Word.ContentControl convertToBlockLevel(Word.ContentControl currentCC, bool keepContents, bool updateScreen)
        {
            Word.Document            document   = Globals.ThisAddIn.Application.ActiveDocument;
            OpenDoPEModel.DesignMode designMode = new OpenDoPEModel.DesignMode(document);

            // Only do it if the content control is rich text
            if (!currentCC.Type.Equals(Word.WdContentControlType.wdContentControlRichText))
            {
                log.Warn("convert to block level only operates on rich text controls, not " + currentCC.Type);
                return(null);
            }

            string majorVersionString = Globals.ThisAddIn.Application.Version.Split(new char[] { '.' })[0];
            int    majorVersion       = Convert.ToInt32(majorVersionString);


            // Only do it if the content control is not already block level
            //
            if (isBlockLevel(currentCC))
            {
                return(currentCC);
            }


            // Can only do this if the content control is not
            // nested within some other inline content control
            if (currentCC.ParentContentControl != null &&
                !isBlockLevel(currentCC.ParentContentControl))
            {
                MessageBox.Show("This content control contains block level content, but can't be converted automatically.  Please correct this yourself, by deleting it, and re-creating at block level.");
                return(null);
            }


            if (majorVersion >= 14)
            {
                getWordApp().UndoRecord.StartCustomRecord("Promote content control to block-level");
            }

            bool ccIsAtPStart = ccStartsAtStartOfParagraph(currentCC);

            object collapseStart = Word.WdCollapseDirection.wdCollapseStart;
            //object collapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
            object unitCharacter = Word.WdUnits.wdCharacter;


            // Get a range start of cc.
            Word.Range ccRange = currentCC.Range;
            ccRange.Collapse(ref collapseStart);

            // Delete the cc, but preserve Tag, Title
            string tagVal   = currentCC.Tag;
            string titleVal = currentCC.Title;
            string contents = currentCC.Range.Text;

            currentCC.Delete(true);

            ccRange.Select();
            if (ccIsAtPStart)
            {
                document.Windows[1].Selection.TypeParagraph();
            }
            else
            {
                // Insert 2 new paragraphs
                document.Windows[1].Selection.TypeParagraph();
                document.Windows[1].Selection.TypeParagraph();
            }

            // Create a cc around the first new p
            object start    = ccRange.Start + 1;
            object end      = ccRange.Start + 1;
            object newRange = document.Range(ref start, ref end);

            log.Info("target {0}, {1}", ((Word.Range)newRange).Start, ((Word.Range)newRange).End);

            designMode.Off();
            Word.ContentControl newCC = document.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref newRange);
            designMode.restoreState();

            newCC.Tag   = tagVal;
            newCC.Title = titleVal;
            if (keepContents) // want to do this for XHTML
            {
                newCC.Range.Text = contents;
            }

            if (updateScreen)
            {
                newCC.Application.ScreenUpdating = true;
                newCC.Application.ScreenRefresh();
            }
            return(newCC);

            // Approach:
            //  .. Get the paragraph
            // .. Make a copy
            // .. in the copy, delete up to our position
            // .. in the original, delete after our position

            //Word.Range splittingPoint = sel.Range;

            //object para1DeleteStartPoint = splittingPoint.Start;

            //Word.Range paraOrig = Globals.ThisAddIn.Application.ActiveDocument.Range(ref para1DeleteStartPoint, ref para1DeleteStartPoint);
            //paraOrig.MoveStart(ref unitParagraph, ref back1);

            //int lengthStartSegment = paraOrig.End - paraOrig.Start;

            //object startPoint = paraOrig.Start;

            //paraOrig.MoveEnd(ref unitParagraph, ref forward1);

            //object endPoint = paraOrig.End;
            //object endPointPlusOne = paraOrig.End + 1;

            //// copy it
            //Word.Range insertPoint = Globals.ThisAddIn.Application.ActiveDocument.Range(ref endPoint, ref endPoint);
            //paraOrig.Copy();
            //insertPoint.Paste();

            //// In the copy, delete the first half
            //// (do this operation first, to preserve our original position calculations)
            //object para2DeleteEndpoint = (int)endPoint + lengthStartSegment;
            //Word.Range para2Deletion = Globals.ThisAddIn.Application.ActiveDocument.Range(ref endPoint, ref para2DeleteEndpoint);
            //para2Deletion.Delete();

            //// In the original, delete the second half
            //Word.Range para1Deletion = Globals.ThisAddIn.Application.ActiveDocument.Range(ref para1DeleteStartPoint, ref endPoint);
            //para1Deletion.Delete();

            if (majorVersion >= 14)
            {
                getWordApp().UndoRecord.EndCustomRecord();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Function which marks the selected text as an Abbreviation\Acronym
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Mark_Click(object sender, EventArgs e) {
            try {
                if (currentDoc.ProtectionType == Microsoft.Office.Interop.Word.WdProtectionType.wdNoProtection) {
                    CustomXMLParts xmlParts = currentDoc.CustomXMLParts;
                    //Checking whether CustomXML is there or not in the Current Document
                    for (int i = 1; i <= xmlParts.Count; i++) {
                        if (xmlParts[i].NamespaceURI == "http://Daisy-OpenXML/customxml") {
                            checkCustomXml = 1;
                        }
                    }

                    //If CustomXML is not there in the Current Document
                    if (checkCustomXml == 0) {
                        //Creating Custom XML document for the Current Document
                        XmlElement elmtManage = manageAbbrAcr.CreateElement("Manage");
                        manageAbbrAcr.AppendChild(elmtManage);
                        elmtManage.SetAttribute("xmlns", "http://Daisy-OpenXML/customxml");

                        XmlElement elmtAbbreviations = manageAbbrAcr.CreateElement("Abbreviations");
                        elmtManage.AppendChild(elmtAbbreviations);

                        XmlElement elmtAcronyms = manageAbbrAcr.CreateElement("Acronyms");
                        elmtManage.AppendChild(elmtAcronyms);

                        //If user is not selected "allOccurrences" checkbox 
                        if (allOccurences == "No") {
                            //If call is from Abbreviation button
                            if (checkAbbrAcr) {
                                object val = System.Reflection.Missing.Value;
                                String nameAbbr = "Abbreviations" + GenerateId().ToString();
                                //Adding Bookmark for the selected Text
                                currentDoc.Application.Selection.Bookmarks.Add(nameAbbr, ref val);

                                //Updating the CustomXML
                                XmlElement elmtItem = manageAbbrAcr.CreateElement("Item");
                                elmtItem.SetAttribute("AbbreviationName", nameAbbr);
                                elmtItem.SetAttribute("FullAbbr", tBx_MarkFullForm.Text.TrimEnd());
                                elmtItem.SetAttribute("OriginalText", currentDoc.Application.Selection.Text.Trim());
                                elmtAbbreviations.AppendChild(elmtItem);

                                //Adding the CustomXml to the Current Document
                                CustomXMLPart part = currentDoc.CustomXMLParts.Add(manageAbbrAcr.InnerXml, System.Reflection.Missing.Value);
                                this.Close();
                            }
                            //If call is from Acronym button
                            else {
                                object val = System.Reflection.Missing.Value;
                                String nameAcr = "Acronyms" + pronounceAbbrAcr + GenerateId().ToString();
                                //Adding Bookmark for the selected Text
                                currentDoc.Application.Selection.Bookmarks.Add(nameAcr, ref val);

                                //Updating the CustomXML
                                XmlElement elmtItem = manageAbbrAcr.CreateElement("Item");
                                elmtItem.SetAttribute("AcronymName", nameAcr);
                                elmtItem.SetAttribute("FullAcr", tBx_MarkFullForm.Text.TrimEnd());
                                elmtItem.SetAttribute("OriginalText", currentDoc.Application.Selection.Text.Trim());
                                elmtAcronyms.AppendChild(elmtItem);

                                //Adding the CustomXml to the Current Document
                                CustomXMLPart part = currentDoc.CustomXMLParts.Add(manageAbbrAcr.InnerXml, System.Reflection.Missing.Value);
                                this.Close();
                            }
                        }
                        //If user is selected "allOccurrences" checkbox 
                        else {
                            //If call is from Abbreviation button
                            if (checkAbbrAcr) {
                                object missing = System.Type.Missing;
                                Object startDoc = 0;
                                Object endDoc = currentDoc.Characters.Count;
                                MSword.Range rngDoc = currentDoc.Range(ref startDoc, ref endDoc);
                                MSword.Find fndDoc = rngDoc.Find;

                                fndDoc.ClearFormatting();
                                fndDoc.Forward = true;
                                fndDoc.Text = currentDoc.Application.Selection.Text.Trim();
                                ExecuteFind(fndDoc);

                                //Applying Abbreviation for all the occurrences of the selected Word
                                while (fndDoc.Found) {
                                    if (ValidateBookMark(rngDoc) == "Nobookmarks") {
                                        String nameAbbr = "Abbreviations" + GenerateId().ToString();
                                        rngDoc.Bookmarks.Add(nameAbbr, ref missing);


                                        XmlElement elmtItem = manageAbbrAcr.CreateElement("Item");
                                        elmtItem.SetAttribute("AbbreviationName", nameAbbr);
                                        elmtItem.SetAttribute("FullAbbr", tBx_MarkFullForm.Text.TrimEnd());
                                        elmtItem.SetAttribute("OriginalText", currentDoc.Application.Selection.Text.Trim());

                                        elmtAbbreviations.AppendChild(elmtItem);
                                    }
                                    ExecuteFind(fndDoc);
                                }

                                //Adding the CustomXml to the Current Document
                                CustomXMLPart part = currentDoc.CustomXMLParts.Add(manageAbbrAcr.InnerXml, System.Reflection.Missing.Value);
                                this.Close();
                            }
                            //If call is from Acronym button
                            else {
                                object missing = System.Type.Missing;
                                Object startDoc = 0;
                                Object endDoc = currentDoc.Characters.Count;
                                MSword.Range rngDoc = currentDoc.Range(ref startDoc, ref endDoc);
                                MSword.Find fndDoc = rngDoc.Find;

                                fndDoc.ClearFormatting();
                                fndDoc.Forward = true;
                                fndDoc.Text = currentDoc.Application.Selection.Text.Trim();
                                ExecuteFind(fndDoc);

                                //Applying Abbreviation for all the occurrences of the selected Word
                                while (fndDoc.Found) {
                                    if (ValidateBookMark(rngDoc) == "Nobookmarks") {
                                        String nameAcr = "Acronyms" + pronounceAbbrAcr + GenerateId().ToString();
                                        rngDoc.Bookmarks.Add(nameAcr, ref missing);

                                        XmlElement elmtItem = manageAbbrAcr.CreateElement("Item");
                                        elmtItem.SetAttribute("AcronymName", nameAcr);
                                        elmtItem.SetAttribute("FullAcr", tBx_MarkFullForm.Text.TrimEnd());
                                        elmtItem.SetAttribute("OriginalText", currentDoc.Application.Selection.Text.Trim());

                                        elmtAcronyms.AppendChild(elmtItem);
                                    }
                                    ExecuteFind(fndDoc);
                                }

                                //Adding the CustomXml to the Current Document
                                CustomXMLPart part = currentDoc.CustomXMLParts.Add(manageAbbrAcr.InnerXml, System.Reflection.Missing.Value);
                                this.Close();
                            }
                        }
                    }
                    //If already CustomXML is there in the Current Document
                    else {
                        //If user is not selected "allOccurrences" checkbox 
                        if (allOccurences == "No") {
                            Individual();
                        } else {
                            AllOccurences();
                        }
                    }
                } else {
                    MessageBox.Show("The current document is locked for editing. Please unprotect the document.", "SaveAsDAISY", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            } catch (Exception ex) {
                MessageBox.Show(ex.Message, "SaveAsDAISY", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 5
0
        public void FillRepotData(Word.Document wordDoc, ReportAllDetailsDocVm reportDocData, string verifiedBy, List <ImageHouse> imageHouses)
        {
            try
            {
                var sfc = reportDocData.SafetyFirstCheck;
                var cus = reportDocData.CustomerEquipmentActivity;

                if (sfc != null && cus != null)
                {
                    wordDoc.SelectContentControlsByTitle("sfc_Customer")[1].Range.Text          = GetValueOrSpace(sfc.ProjectName);
                    wordDoc.SelectContentControlsByTitle("sfc_ServiceEngineer")[1].Range.Text   = GetValueOrSpace(sfc.EngineerName);
                    wordDoc.SelectContentControlsByTitle("sfc_Job_No")[1].Range.Text            = GetValueOrSpace(sfc.JobOrderNumber);
                    wordDoc.SelectContentControlsByTitle("sfc_startdate")[1].Range.Text         = sfc.StartDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("sfc_contactno")[1].Range.Text         = GetValueOrSpace(sfc.ContactNumber);
                    wordDoc.SelectContentControlsByTitle("sfc_sitesafetycontact")[1].Range.Text = GetValueOrSpace(sfc.SiteSafetyContact);
                    wordDoc.SelectContentControlsByTitle("sfc_addcomm")[1].Range.Text           = GetValueOrSpace(sfc.AdditionalComments);

                    if (!string.IsNullOrWhiteSpace(sfc.Participants))
                    {
                        var participants = sfc.Participants.Split('\n');
                        var firstFive    = string.Empty;
                        var secondFive   = string.Empty;
                        int midPoint     = participants.Length / 2;
                        for (int i = 0; i < participants.Length; i++)
                        {
                            if (i <= midPoint)
                            {
                                firstFive += participants[i] + '\n';
                            }
                            else
                            {
                                secondFive += participants[i] + '\n';
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(firstFive))
                        {
                            firstFive = firstFive.Remove(firstFive.LastIndexOf('\n'));
                            wordDoc.SelectContentControlsByTitle("sfc_participants")[1].Range.Text = firstFive;
                            wordDoc.SelectContentControlsByTitle("sfc_participants")[1].Range.ListFormat.ApplyNumberDefault();
                        }
                        if (!string.IsNullOrWhiteSpace(secondFive))
                        {
                            secondFive = secondFive.Remove(secondFive.LastIndexOf('\n'));
                            wordDoc.SelectContentControlsByTitle("sfc_participants_1")[1].Range.Text = secondFive;
                            wordDoc.SelectContentControlsByTitle("sfc_participants_1")[1].Range.ListFormat.ApplyNumberDefault();
                        }
                    }

                    wordDoc.SelectContentControlsByTitle("sfc_signdate")[1].Range.Text = sfc.SignDate?.ToString("dd/MM/yy");
                    var sfcDetails = sfc.SafetyFirstCheckDetails;
                    if (sfcDetails != null)
                    {
                        var sfcd1 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "STOP-THINK-ACT");
                        if (sfcd1 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_stopthinkact")[1].Checked = sfcd1.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_stopthinkact_rm")[1].Range.Text = GetValueOrSpace(sfcd1?.Remarks);
                        var sfcd2 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Permit to Work(PTW)");
                        if (sfcd2 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_ptw")[1].Checked = sfcd2.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_ptw_rm")[1].Range.Text = GetValueOrSpace(sfcd2.Remarks);
                        var sfcd3 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Fitness of Personnel");
                        if (sfcd3 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_fitness")[1].Checked = sfcd3.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_fitness_rm")[1].Range.Text = GetValueOrSpace(sfcd3.Remarks);
                        var sfcd4 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Work Area Evaluation");
                        if (sfcd4 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_workareaeval")[1].Checked = sfcd4.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_workareaeval_rm")[1].Range.Text = GetValueOrSpace(sfcd4.Remarks);
                        var sfcd5 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Evacuation Plan");
                        if (sfcd5 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_evalplan")[1].Checked = sfcd5.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_evalplan_rm")[1].Range.Text = GetValueOrSpace(sfcd5.Remarks);
                        var sfcd6 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Method Statement Review");
                        if (sfcd6 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_methstmtrev")[1].Checked = sfcd6.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_methstmtrev_rm")[1].Range.Text = GetValueOrSpace(sfcd6.Remarks);
                        var sfcd7 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Risk Assessment Review");
                        if (sfcd7 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_riskassessrev")[1].Checked = sfcd7.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_riskassessrev_rm")[1].Range.Text = GetValueOrSpace(sfcd7.Remarks);
                        var sfcd8 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Mandatory PPE");
                        if (sfcd8 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_madatoryppe")[1].Checked = sfcd8.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_madatoryppe_rm")[1].Range.Text = GetValueOrSpace(sfcd8.Remarks);
                        var sfcd9 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "Condition of tools/gears");
                        if (sfcd9 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_cond_tools")[1].Checked = sfcd9.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_cond_tools_rm")[1].Range.Text = GetValueOrSpace(sfcd9.Remarks);
                        var sfcd10 = sfcDetails.FirstOrDefault(f => f.CheckPointName == "First Aid");
                        if (sfcd10 != null)
                        {
                            wordDoc.SelectContentControlsByTitle($"sfc_firstaid")[1].Checked = sfcd10.IsSelected;
                        }
                        wordDoc.SelectContentControlsByTitle($"sfc_firstaid_rm")[1].Range.Text = GetValueOrSpace(sfcd10.Remarks);
                    }
                    wordDoc.SelectContentControlsByTitle("Job_No_Header")[1].Range.Text = GetValueOrSpace(sfc.JobOrderNumber);
                    //wordDoc.SelectContentControlsByTitle("Sub_No_Header")[1].Range.Text = GetValueOrSpace(sfc.JobOrderNumber);

                    wordDoc.SelectContentControlsByTitle("Cea_Customer")[1].Range.Text            = GetValueOrSpace(sfc.ProjectName);
                    wordDoc.SelectContentControlsByTitle("Cea_ServiceEngineer")[1].Range.Text     = GetValueOrSpace(sfc.EngineerName);
                    wordDoc.SelectContentControlsByTitle("Cea_ReportNumber")[1].Range.Text        = GetValueOrSpace(sfc.JobOrderNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_PreviousServiceDate")[1].Range.Text = cus.PreviousServiceDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_CurrentServiceDate")[1].Range.Text  = cus.CurrentServiceDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_ReportDate")[1].Range.Text          = cus.ReportDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle("Cea_SiteLocation")[1].Range.Text        = GetValueOrSpace(cus.SiteLocation);

                    var equipmentMapping = new Dictionary <string, string> {
                        { "decanter", "Decanter" }
                    };
                    if (equipmentMapping.TryGetValue(cus.Equipment, out string Equipment))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_Equipment", Equipment);
                    }

                    //equipment details
                    wordDoc.SelectContentControlsByTitle("Cea_DecanterModel")[1].Range.Text        = GetValueOrSpace(cus.DecanterModel);
                    wordDoc.SelectContentControlsByTitle("Cea_DecanterSerialNumber")[1].Range.Text = GetValueOrSpace(cus.DecanterSerialNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_BowlSerialNumber")[1].Range.Text     = GetValueOrSpace(cus.BowlSerialNumber);
                    wordDoc.SelectContentControlsByTitle("Cea_CustomerReference")[1].Range.Text    = GetValueOrSpace(cus.CustomerReference);
                    wordDoc.SelectContentControlsByTitle("Cea_RunningHours")[1].Range.Text         = cus.RunningHours.ToString();

                    wordDoc.SelectContentControlsByTitle("Cea_Controller")[1].Range.Text   = GetValueOrSpace(cus.Controller);
                    wordDoc.SelectContentControlsByTitle("Cea_HmiModel")[1].Range.Text     = GetValueOrSpace(cus.HmiModel);
                    wordDoc.SelectContentControlsByTitle("Cea_HmiSwVersion")[1].Range.Text = GetValueOrSpace(cus.HmiSwVersion);
                    wordDoc.SelectContentControlsByTitle("Cea_CpuModel")[1].Range.Text     = GetValueOrSpace(cus.CpuModel);
                    wordDoc.SelectContentControlsByTitle("Cea_CpuSwVersion")[1].Range.Text = GetValueOrSpace(cus.CpuSwVersion);

                    //if(KeyValue.controllerMapping.TryGetValue(cus.Controller, out string controller))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_Controller", controller);

                    //if (KeyValue.hmiModelMapping.TryGetValue(cus.HmiModel, out string hmiModel))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_HmiModel", hmiModel);

                    //if (KeyValue.HmiSwVersionMapping.TryGetValue(cus.HmiSwVersion, out string hmiSwVersion))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_HmiSwVersion", hmiSwVersion);

                    //if (KeyValue.CpuModelMapping.TryGetValue(cus.CpuModel, out string CpuModel))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_CpuModel", CpuModel);

                    //if (KeyValue.CpuSwVersionMapping.TryGetValue(cus.CpuSwVersion, out string CpuSwVersion))
                    //    SelectValueFromDropDownSrc(wordDoc, "Cea_CpuSwVersion", CpuSwVersion);

                    //Activity
                    if (KeyValue.ScopeOfWrokMapping.TryGetValue(cus.ScopeOfWrok, out string ScopeOfWrok))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_ScopeOfWrok", ScopeOfWrok);
                    }
                    wordDoc.SelectContentControlsByTitle("Cea_ScoperOfWorkOthers")[1].Range.Text = GetValueOrSpace(cus.ScoperOfWorkOthers);

                    if (KeyValue.WorkStatusMapping.TryGetValue(cus.WorkStatus, out string WorkStatus))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_WorkStatus", WorkStatus);
                    }

                    if (KeyValue.DecanterStatusMapping.TryGetValue(cus.DecanterStatus, out string DecanterStatus))
                    {
                        SelectValueFromDropDownSrc(wordDoc, "Cea_DecanterStatus", DecanterStatus);
                    }
                }

                //Vibration Analysis Report
                var vibAna = reportDocData.VibrationAnalysisHeader;
                if (vibAna != null)
                {
                    wordDoc.SelectContentControlsByTitle($"Vah_BsDryRunActive")[1].Checked = vibAna.BsDryRunActive;
                    wordDoc.SelectContentControlsByTitle($"Vah_BsProduction")[1].Checked   = vibAna.BsProduction;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsDryRun")[1].Checked       = vibAna.AsDryRun;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsWaterTest")[1].Checked    = vibAna.AsWaterTest;
                    wordDoc.SelectContentControlsByTitle($"Vah_AsProduction")[1].Checked   = vibAna.AsProduction;

                    if (vibAna.VibrationAnalysis != null && vibAna.VibrationAnalysis.Count > 0)
                    {
                        foreach (var pu in KeyValue.parameterUnits)
                        {
                            var param = vibAna.VibrationAnalysis?.Where(w => $"{w.Parameter}~{w.Units}" == pu.Value).FirstOrDefault();
                            if (param != null)
                            {
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_DryRun")[1].Range.Text = GetValueOrSpace(param.BsDryRun);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_Prod")[1].Range.Text   = GetValueOrSpace(param.BsProduction);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_DryRun")[1].Range.Text = GetValueOrSpace(param.AsDryRun);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Water")[1].Range.Text  = GetValueOrSpace(param.AsWaterTest);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Prod")[1].Range.Text   = GetValueOrSpace(param.AsProduction);
                            }
                            else
                            {
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_DryRun")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_Bs_Prod")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_DryRun")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Water")[1].Delete(true);
                                wordDoc.SelectContentControlsByTitle($"{pu.Key}_As_Prod")[1].Delete(true);
                            }
                        }
                    }

                    wordDoc.SelectContentControlsByTitle($"Md_Check")[1].Checked = vibAna.MdMotor;
                    wordDoc.SelectContentControlsByTitle($"Bd_Check")[1].Checked = vibAna.BdMotor;

                    wordDoc.SelectContentControlsByTitle($"Md_DE_Main")[1].Range.Text  = GetValueOrSpace(vibAna.MdDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Md_NDE_Main")[1].Range.Text = GetValueOrSpace(vibAna.MdNonDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Md_DE_Back")[1].Range.Text  = GetValueOrSpace(vibAna.MdDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Md_NDE_Back")[1].Range.Text = GetValueOrSpace(vibAna.MdNonDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Bd_DE_Main")[1].Range.Text  = GetValueOrSpace(vibAna.BdDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Bd_NDE_Main")[1].Range.Text = GetValueOrSpace(vibAna.BdNonDriveEndMain);
                    wordDoc.SelectContentControlsByTitle($"Bd_DE_Back")[1].Range.Text  = GetValueOrSpace(vibAna.BdDriveEndBack);
                    wordDoc.SelectContentControlsByTitle($"Bd_NDE_Back")[1].Range.Text = GetValueOrSpace(vibAna.BdNonDriveEndBack);
                    wordDoc.SelectContentControlsByTitle("Vah_Remarks")[1].Range.Text  = GetValueOrSpace(vibAna.Remarks);
                    if (!string.IsNullOrWhiteSpace(vibAna.Remarks))
                    {
                        wordDoc.SelectContentControlsByTitle("Vah_Remarks")[1].Range.Font.Color = Word.WdColor.wdColorRed;
                    }
                }

                bool pageBreakedRecomm     = false;
                bool pageBreakedObs        = false;
                bool pageBreakedSpareParts = false;


                #region Recommendations
                var recommTableIndex = 0;

                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "RecommHead")
                    {
                        recommTableIndex = i;
                        break;
                    }
                }
                if (recommTableIndex > 0 && reportDocData.Recommendations != null && reportDocData.Recommendations.Count > 0)
                {
                    wordDoc.Tables[recommTableIndex].Range.InsertBreak();
                    pageBreakedRecomm = true;
                    int sno = 1;
                    foreach (var recomm in reportDocData.Recommendations)
                    {
                        var row = wordDoc.Tables[recommTableIndex].Rows.Add();
                        row.Height     = 30.0f; //1.2 cm
                        row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                        row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                        row.Cells[1].Range.Text      = $"0{sno}";
                        row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                        row.Cells[1].Range.Font.Bold = 0;

                        row.Cells[2].Range.Text      = GetValueOrSpace(recomm.Remarks);
                        row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                        row.Cells[2].Range.Font.Bold = 0;
                        row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                        row.Cells[3].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.ImmediateAction;
                        row.Cells[4].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.MidTermAction;
                        row.Cells[5].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = recomm.Observation;
                        sno++;
                        //InsertOrRemoveImage(wordDoc, $"Recomm_Pic_{i}", recomm.EntityRefGuid, imageHouses);
                    }
                }
                else
                {
                    //wordDoc.SelectContentControlsByTitle("RecommHead")[1].Delete(true);
                    //if (recommTableIndex > 0)
                    //    wordDoc.Tables[recommTableIndex].Delete();

                    //Client Req:Recommendations can be added. But the page is getting skipped in Report
                    var row = wordDoc.Tables[recommTableIndex].Rows.Add();
                    row.Height     = 30.0f; //1.2 cm
                    row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                    row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                    row.Cells[1].Range.Text      = $"0{1}";
                    row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                    row.Cells[1].Range.Font.Bold = 0;

                    row.Cells[2].Range.Text      = string.Empty;
                    row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                    row.Cells[2].Range.Font.Bold = 0;
                    row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                    row.Cells[3].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;
                    row.Cells[4].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;
                    row.Cells[5].Range.ContentControls.Add(Word.WdContentControlType.wdContentControlCheckBox).Checked = false;

                    pageBreakedRecomm = true;
                }
                #endregion

                #region Observations
                var obserTableIndex = 0;
                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "ObsHead")
                    {
                        obserTableIndex = i;
                        break;
                    }
                }

                if (obserTableIndex > 0 && reportDocData.Observations != null &&
                    reportDocData.Observations.Count > 0)
                {
                    if (pageBreakedRecomm)
                    {
                        wordDoc.Tables[obserTableIndex].Range.InsertBreak();
                    }

                    pageBreakedObs = true;
                    int iteration = 0;
                    foreach (var obs in reportDocData.Observations)
                    {
                        //if (!KeyValue.observation.ContainsKey(obs.Title))
                        //    continue;

                        Word.Row row1 = null;
                        Word.Row row2 = null;
                        if (iteration > 0)
                        {
                            row1 = wordDoc.Tables[obserTableIndex].Rows.Add();
                            row2 = wordDoc.Tables[obserTableIndex].Rows.Add();
                        }
                        else
                        {
                            row1 = wordDoc.Tables[obserTableIndex].Rows[1];
                            row2 = wordDoc.Tables[obserTableIndex].Rows.Add();
                        }
                        row1.Height     = 30.0f;
                        row1.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;

                        row2.Height     = 30.0f;
                        row2.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;

                        row1.Borders[Word.WdBorderType.wdBorderTop].LineStyle    = Word.WdLineStyle.wdLineStyleDouble;
                        row2.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

                        //row1
                        row1.Cells[1].Range.Text = obs.Title;

                        string remark = $"Observations:";
                        if (!string.IsNullOrWhiteSpace(obs.Remarks))
                        {
                            remark = $"Observations:\n{obs.Remarks}";
                        }
                        row1.Cells[2].Range.Text      = remark;
                        row1.Cells[2].Range.Font.Bold = 0;
                        row1.Cells[2].Range.ListFormat.ApplyBulletDefault();

                        //making Observations: as Bold & removing bullet
                        object     objStart = row1.Cells[2].Range.Start;
                        object     objEnd   = row1.Cells[2].Range.Start + remark.IndexOf(":");
                        Word.Range rngBold  = wordDoc.Range(ref objStart, ref objEnd);
                        rngBold.Bold = 1;
                        rngBold.ListFormat.RemoveNumbers();

                        //row2
                        string imagePath = GetImagePath(obs.EntityRefGuid, imageHouses);

                        if (!string.IsNullOrWhiteSpace(imagePath) && System.IO.File.Exists(imagePath))
                        {
                            row2.Height     = 120.0f;
                            row2.HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;

                            row2.Cells[1].Range.ContentControls
                            .Add(Word.WdContentControlType.wdContentControlPicture).Range
                            .InlineShapes.AddPicture(imagePath);
                        }
                        string actionTaken = $"Action Taken:";
                        if (!string.IsNullOrWhiteSpace(obs.ActionTaken))
                        {
                            actionTaken = $"Action Taken: {obs.ActionTaken}";
                        }

                        row2.Cells[2].Range.Text      = actionTaken;
                        row2.Cells[2].Range.Font.Bold = 0;
                        row2.Cells[2].Range.ListFormat.ApplyBulletDefault();

                        //making Action Taken: as Bold & removing bullet
                        object     objStart1 = row2.Cells[2].Range.Start;
                        object     objEnd1   = row2.Cells[2].Range.Start + actionTaken.IndexOf(":");
                        Word.Range rngBold1  = wordDoc.Range(ref objStart1, ref objEnd1);
                        rngBold1.Bold = 1;
                        rngBold1.ListFormat.RemoveNumbers();

                        iteration++;
                    }

                    #region Merging Cells
                    Word.Table table = wordDoc.Tables[obserTableIndex];
                    Word.Cell  cell;
                    int        rowIndex     = 1;
                    int        blockIndex   = table.Rows.Count / 2;
                    int        coloumnIndex = 1;

                    for (int blockCounter = 1; blockCounter <= blockIndex; blockCounter++)
                    {
                        for (int colCounter = 1; colCounter <= coloumnIndex; colCounter++)
                        {
                            cell = table.Cell(rowIndex, colCounter);
                            cell.Merge(table.Cell(cell.RowIndex + 1, colCounter));
                        }
                        rowIndex += 2;
                    }
                    #endregion
                }
                else
                {
                    wordDoc.SelectContentControlsByTitle("ObsHead")[1].Delete(true);
                    if (obserTableIndex > 0)
                    {
                        wordDoc.Tables[obserTableIndex].Delete();
                    }
                }
                #endregion

                #region Spare Parts
                var sparePartTypes = new string[] { "USED", "RECOM" };
                int sparePartIter  = 0;
                foreach (var sparePart in sparePartTypes)
                {
                    var sparePartsTableIndex = 0;

                    for (int i = 1; i <= wordDoc.Tables.Count; i++)
                    {
                        if (wordDoc.Tables[i].Title == sparePart)
                        {
                            sparePartsTableIndex = i;
                            break;
                        }
                    }
                    if (sparePartsTableIndex > 0 && reportDocData.SpareParts != null && reportDocData.SpareParts.Count > 0)
                    {
                        if (sparePartIter == 0)
                        {
                            wordDoc.Tables[sparePartsTableIndex].Range.InsertBreak();
                            pageBreakedSpareParts = true;
                            sparePartIter++;
                        }

                        int sno = 1;
                        foreach (var sp in reportDocData.SpareParts.Where(w => sparePart.Equals(w.Type, StringComparison.OrdinalIgnoreCase)))
                        {
                            var row = wordDoc.Tables[sparePartsTableIndex].Rows.Add();
                            row.Height     = 25.0f; //1.0 cm
                            row.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
                            row.Shading.BackgroundPatternColor = Word.WdColor.wdColorWhite;

                            row.Cells[1].Range.Text      = $"{sno}";
                            row.Cells[1].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[1].Range.Font.Bold = 0;

                            row.Cells[2].Range.Text      = GetValueOrSpace(sp.Description);
                            row.Cells[2].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[2].Range.Font.Bold = 0;
                            row.Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                            row.Cells[3].Range.Text      = GetValueOrSpace(sp.PartNo);
                            row.Cells[3].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[3].Range.Font.Bold = 0;
                            row.Cells[3].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                            row.Cells[4].Range.Text      = sp.Quantity.ToString();
                            row.Cells[4].Range.Underline = Word.WdUnderline.wdUnderlineNone;
                            row.Cells[4].Range.Font.Bold = 0;
                            row.Cells[4].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            sno++;
                        }
                    }
                    else
                    {
                        //wordDoc.SelectContentControlsByTitle(sparePart)[1].Delete(true);
                        if (sparePartsTableIndex > 0)
                        {
                            wordDoc.Tables[sparePartsTableIndex].Delete();
                        }
                    }
                }

                #endregion

                //Ack //misc --SignCommSection
                var commTableIndex = 0;
                for (int i = 1; i <= wordDoc.Tables.Count; i++)
                {
                    if (wordDoc.Tables[i].Title == "SignCommSection")
                    {
                        commTableIndex = i;
                        break;
                    }
                }
                if (pageBreakedObs || pageBreakedRecomm || pageBreakedSpareParts)
                {
                    wordDoc.Tables[commTableIndex].Range.InsertBreak();
                }

                var miscData = reportDocData.Misc;
                if (miscData != null)
                {
                    wordDoc.SelectContentControlsByTitle($"misc_firmcomm")[1].Range.Text = GetValueOrSpace(miscData.FirmComments);
                    wordDoc.SelectContentControlsByTitle($"misc_custcomm")[1].Range.Text = GetValueOrSpace(miscData.CustomerComments);
                    wordDoc.SelectContentControlsByTitle($"Alfa_Ack_Name")[1].Range.Text = GetValueOrSpace(miscData.FirmName);
                    wordDoc.SelectContentControlsByTitle($"Alfa_Ack_Date")[1].Range.Text = miscData.FirmDate.ToString("dd/MM/yy");
                    wordDoc.SelectContentControlsByTitle($"Cust_Ack_Name")[1].Range.Text = GetValueOrSpace(miscData.CustomerName);
                    wordDoc.SelectContentControlsByTitle($"Cust_Ack_Date")[1].Range.Text = miscData.CustomerDate.ToString("dd/MM/yy");;
                }
                var firmSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.FirmSignature);
                if (firmSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "firm_sign", firmSignature.EntityRefGuid, imageHouses);
                }
                var custSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.CustomerSignature);
                if (custSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "cust_sign", custSignature.EntityRefGuid, imageHouses);
                }

                var sfc_firmSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.SfcFirmSignature);
                if (sfc_firmSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "sfc_firmsign", sfc_firmSignature.EntityRefGuid, imageHouses);
                }
                var sfc_custSignature = imageHouses.FirstOrDefault(w => w.ImageLabel == StringConstants.SfcCustomerSignature);
                if (sfc_custSignature != null)
                {
                    InsertOrRemoveImage(wordDoc, "sfc_customersign", sfc_custSignature.EntityRefGuid, imageHouses);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 6
0
        private string GetBetterImgFinal(int rangeStart, int RangeEnd)
        {
            Range rangeFrom = WordDoc.Range(rangeStart, RangeEnd);

            rangeFrom.Copy();

            Range range = Globals.ThisAddIn.Application.ActiveDocument.Range();

            range.Font.Name = "宋体";
            range.Font.Size = (float)5;
            Globals.ThisAddIn.Application.ActiveDocument.Range().Text = "                                                                                                                                                                                               ";
            Globals.ThisAddIn.Application.ActiveWindow.ScrollIntoView(range);


            range.SetRange(0, 0);
            range.Select();
            System.Drawing.Point leftTopPos = GetPositionForShowing(Globals.ThisAddIn.Application.Selection);

            range = Globals.ThisAddIn.Application.ActiveDocument.Range();
            range.SetRange(range.End, range.End);
            range.Select();
            System.Drawing.Point rightTopPos = GetPositionForShowing(Globals.ThisAddIn.Application.Selection);

            range.Text = "\n";
            range      = Globals.ThisAddIn.Application.ActiveDocument.Range();
            range.SetRange(range.End, range.End);
            range.Select();
            range.Paste();



            range = Globals.ThisAddIn.Application.ActiveDocument.Range();
            range.SetRange(range.End, range.End);
            range.Font.Name = "宋体";
            range.Font.Size = (float)5;
            range.Text      = "\n  ";

            range.SetRange(0, 0);
            Globals.ThisAddIn.Application.ActiveWindow.ScrollIntoView(range);

            range = Globals.ThisAddIn.Application.ActiveDocument.Range();
            range.SetRange(range.End - 1, range.End);
            range.Select();

            System.Threading.Thread.Sleep(1000);
            System.Drawing.Point buttomPos = GetPositionForShowing(Globals.ThisAddIn.Application.Selection);

            range = Globals.ThisAddIn.Application.ActiveDocument.Range();
            range.GrammarChecked  = false;
            range.SpellingChecked = false;

            System.Threading.Thread.Sleep(1000);
            Bitmap   image = new Bitmap(rightTopPos.X - leftTopPos.X + 10, buttomPos.Y - leftTopPos.Y - 20);
            Graphics g     = Graphics.FromImage(image);

            g.CopyFromScreen(leftTopPos.X, leftTopPos.Y, 0, 0, image.Size);

            string fileName = System.Guid.NewGuid().ToString();

            image.Save(@"D:\新建文件夹\" + fileName + ".png", System.Drawing.Imaging.ImageFormat.Png);



            this.button7.Text = "leftTop" + leftTopPos.X + ":" + leftTopPos.Y + "rightTop" + rightTopPos.X + ":" + rightTopPos.Y + "Buttom" + buttomPos.X + ":" + buttomPos.Y;

            //WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

            return(fileName + ".png");
        }
Ejemplo n.º 7
0
        private void buttonPDF_Click(object sender, RoutedEventArgs e)
        {
            var wrd_name = Convert.ToString(comboBox.SelectedValue);
            var xls_name = textBoxExcelPath.Text;

            if (string.IsNullOrEmpty(wrd_name))
            {
                MessageBox.Show("Выберите шаблон КП");
                return;
            }

            ProgressWnd pw = new ProgressWnd("Создаем КП по шаблону...");
            pw.Show();

            string fn = "";
            try
            {

                WordApp = new Wd.Application() { Visible = false };
                WordDoc = WordApp.Documents.Open(wrd_name);
                fn=SaveW(WordApp, WordDoc);

                var ad = DataContext as AllData;

                ReplaceAll(WordDoc,"[OurCompany]", ad.Our.OurCompany);
                ReplaceAll(WordDoc, "[ForWho]", ad.ForWho);
                ReplaceAll(WordDoc, "[ContractPeriodYears]", ad.HowLongYears);
                ReplaceAll(WordDoc, "[ServiceType]", ad.ServiceType);
                ReplaceAll(WordDoc, "[DaysToStart]", ad.DaysToStart);
                ReplaceAll(WordDoc, "[DateStart]", ad.DateStart);
                ReplaceAll(WordDoc, "[CostMonthString]", ad.CostMonthString);
                ReplaceAll(WordDoc, "[CostMonth]", ad.CostMonth);
                ReplaceAll(WordDoc, "[CostYear]", (o2d(ad.CostMonth) * 12).ToString());
                ReplaceAll(WordDoc, "[Address]", ad.Address);
                ReplaceAll(WordDoc, "[Date]", ad.Date);
                ReplaceAll(WordDoc, "[Area]", ad.Area.ToString());
                ReplaceAll(WordDoc, "[NameObject]", ad.ForWho);

                int kk = 1;
                foreach(var ee in ad.e1)
                {
                    var trg="[Extra" + kk + "]";
                    if (ee.IsSelected==true)
                    {
                        ReplaceAll(WordDoc, trg, ee.Text);
                    }
                    else
                    {
                        WordDoc.Bookmarks["bExtra" + kk].Range.Delete();
                        ReplaceAll(WordDoc, trg, "");
                    }
                    ++kk;
                }

                kk = 1;
                foreach (var ee in ad.e2)
                {
                    var trg = "[Sod" + kk + "]";
                    if (ee.IsSelected == true)
                    {
                        ReplaceAll(WordDoc, trg, ee.Text);
                    }
                    else
                    {
                        WordDoc.Bookmarks["bSod" + kk].Range.Delete();
                        ReplaceAll(WordDoc, trg, "");
                    }
                    ++kk;
                }

                if(radioButton.IsChecked==true)
                {
                    ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn1);
                }
                else
                {
                    ReplaceAll(WordDoc, "[NaOsnovanii]", ad.NaOsn2);
                }

                if(checkBoxServicePlan.IsChecked==false)
                {
                    Wd.Range delRange = WordDoc.Range();
                    delRange.Start=WordDoc.Bookmarks["b0"].Range.Start;
                    delRange.End = WordDoc.Bookmarks["b1"].Range.End;
                    delRange.Delete();

                }
                ReplaceAll(WordDoc, "[ServicePlanStart]", "");
                ReplaceAll(WordDoc, "[ServicePlanEnd]", "");
                //ReplaceAll(WordDoc, "[NameCost]", ad.ForWho);

                //Sebestoimost
                Wd.Table tt=FindTable(WordDoc, WordDoc.Bookmarks["tab6"]);

                double total = 0;
                foreach (var s in ad.Sebestimost)
                {
                    tt.Rows.Add();

                    tt.Cell(tt.Rows.Count, 1).Range.Text = s.Name;
                    tt.Cell(tt.Rows.Count, 2).Range.Text = s.CostMonth.ToString();
                    total += s.CostMonth;
                }
                tt.Rows.Add();
                tt.Cell(tt.Rows.Count, 1).Range.Text = "Итого";
                tt.Cell(tt.Rows.Count, 2).Range.Text = total.ToString();
                ///

                //FOT
                Wd.Table ttFOT = FindTable(WordDoc, WordDoc.Bookmarks["tab7"]);

                total = 0;
                foreach (var s in ad.ShtatRasstanovka)
                {
                    ttFOT.Rows.Add();

                    ttFOT.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString();
                    ttFOT.Cell(tt.Rows.Count, 2).Range.Text = s.Name;
                    ttFOT.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString();
                    ttFOT.Cell(tt.Rows.Count, 4).Range.Text = s.Smena.ToString();
                }
                ////

                //os sredstv
                Wd.Table ttOS = FindTable(WordDoc, WordDoc.Bookmarks["tab8"]);

                total = 0;
                foreach (var s in ad.OsnSredstva)
                {
                    ttOS.Rows.Add();

                    ttOS.Cell(tt.Rows.Count, 1).Range.Text = s.Num.ToString()+".";
                    ttOS.Cell(tt.Rows.Count, 2).Range.Text = s.Name;
                    ttOS.Cell(tt.Rows.Count, 3).Range.Text = s.Quant.ToString();
                    ttOS.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString();

                    total += s.CostMonth;
                }
                ttOS.Rows.Add();
                ttOS.Cell(tt.Rows.Count, 1).Range.Text = "Итого";
                ttOS.Cell(tt.Rows.Count, 4).Range.Text = total.ToString();

                //rash san
                Wd.Table ttSAN = FindTable(WordDoc, WordDoc.Bookmarks["tab9"]);

                total = 0;
                foreach (var s in ad.RashMaterials)
                {
                    ttSAN.Rows.Add();

                    ttSAN.Cell(tt.Rows.Count, 1).Range.Text = s.Name;
                    ttSAN.Cell(tt.Rows.Count, 2).Range.Text = s.Quant.ToString();
                    ttSAN.Cell(tt.Rows.Count, 3).Range.Text = s.Price.ToString();
                    ttSAN.Cell(tt.Rows.Count, 4).Range.Text = s.CostMonth.ToString();

                    total += s.CostMonth;
                }
                ttSAN.Rows.Add();
                ttSAN.Cell(tt.Rows.Count, 1).Range.Text = "Итого в месяц";
                ttSAN.Cell(tt.Rows.Count, 4).Range.Text = total.ToString();

                StringBuilder sb = new StringBuilder();
                foreach(var c in ad.Contacts)
                {
                    if(c.IsSelected)
                    {
                        sb.AppendLine(c.Dolj);
                        sb.AppendLine(c.Name);
                        sb.AppendLine(c.Tel);
                        sb.AppendLine(c.MobTel);
                        sb.AppendLine(c.Email);
                        sb.AppendLine();
                    }
                }
                ReplaceAll(WordDoc, "[Contacts]", sb.ToString());

                WordDoc.TablesOfContents[1].Update();

                foreach (Wd.Range docRange in WordDoc.Words)
                {
                    docRange.HighlightColorIndex = Wd.WdColorIndex.wdNoHighlight;
                }

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            finally
            {
                WordDoc.Save();
                WordApp.Documents.Close();
                WordApp.Quit(Wd.WdSaveOptions.wdDoNotSaveChanges);

                string convertedXpsDoc = string.Concat(System.IO.Path.GetTempPath(), "\\", Guid.NewGuid().ToString(), ".xps");
                XpsDocument xpsDocument = ConvertWordToXps(fn, convertedXpsDoc);
                if (xpsDocument != null)
                {
                    documentViewer.Document = xpsDocument.GetFixedDocumentSequence();
                }

                pw.Stop();

            }

            // doc.Content.Find.Execute("[ND]", ReplaceWith: Doc.No);

            //   SaveW(app, doc, TemplateFilePath);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获取指定页的 Range。。。
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public Range GetPages(int pageIndex)
        {
            object objWhat  = WdGoToItem.wdGoToPage;
            object objWhich = WdGoToDirection.wdGoToAbsolute;
            object oMissing = System.Reflection.Missing.Value;
            object objPage  = pageIndex;
            Range  range1   = wordDoc.GoTo(ref objWhat, ref objWhich, ref objPage, ref oMissing);
            Range  range2   = range1.GoToNext(WdGoToItem.wdGoToPage);
            object objStart = range1.Start;
            object objEnd   = range2.Start;

            if (range1.Start == range2.Start)
            {
                objEnd = wordDoc.Content.End;
            }
            else
            {
                objEnd = range2.Start - 1;
            }

            return(wordDoc.Range(ref objStart, ref objEnd));
        }
 private void metroTileExportWord_Click(object sender, EventArgs e)
 {
     try
     {
         int did                        = Convert.ToInt32(dataGridViewDistribution.SelectedCells[0].Value.ToString());
         var query                      = db.Distributions.Include(g => g.Graduate).Include(o => o.Organization).Include(p => p.Position);
         var distribution               = query.SingleOrDefault(d => d.DistributionId == did);
         Word.Application app           = new Word.Application();
         Word.Document    doc           = new Word.Document();
         Word.Range       r             = doc.Range();
         Word.Table       table         = doc.Tables.Add(r, 9, 2);
         object           begCell       = table.Cell(1, 1).Range.Start;
         object           endCell       = table.Cell(1, 2).Range.End;
         Word.Range       wordcellrange = doc.Range(ref begCell, ref endCell);
         wordcellrange.Select();
         app.Selection.Cells.Merge();
         table.Cell(1, 1).Range.Text = "Распределение №" + distribution.DistributionId;
         table.Borders.Enable        = 0;
         table.Cell(2, 1).Range.Text = "Фамилия:";
         table.Cell(3, 1).Range.Text = "Имя:";
         table.Cell(4, 1).Range.Text = "Отчество:";
         table.Cell(5, 1).Range.Text = "Организация:";
         table.Cell(6, 1).Range.Text = "Должность:";
         table.Cell(7, 1).Range.Text = "Оклад:";
         table.Cell(8, 1).Range.Text = "Дата начала распределения:";
         table.Cell(9, 1).Range.Text = "Дата окончания распределения:";
         r.Bold      = 0;
         r.Font.Size = 14;
         table.Cell(2, 2).Range.Text = distribution.Graduate.GraduateSurName.ToString();
         table.Cell(3, 2).Range.Text = distribution.Graduate.GraduateFirstName.ToString();
         table.Cell(4, 2).Range.Text = distribution.Graduate.GraduateSecondName.ToString();
         table.Cell(5, 2).Range.Text = distribution.Organization.OrganizationName.ToString();
         table.Cell(6, 2).Range.Text = distribution.Position.PositionName.ToString();
         table.Cell(7, 2).Range.Text = distribution.DistributionSalary.ToString();
         table.Cell(8, 2).Range.Text = distribution.DistributionStart.ToString();
         table.Cell(9, 2).Range.Text = distribution.DistributionEnd.ToString();
         foreach (Word.Row row in table.Rows)
         {
             foreach (Word.Cell cell in row.Cells)
             {
                 if (cell.RowIndex == 1)
                 {
                     cell.Range.Bold                      = 1;
                     cell.Range.Font.Name                 = "Times New Roman";
                     cell.Range.Font.Size                 = 16;
                     cell.Range.Borders.Enable            = 0;
                     cell.VerticalAlignment               = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                     cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                 }
                 else
                 {
                     cell.Range.Borders.Enable            = 0;
                     cell.Range.Font.Name                 = "Times New Roman";
                     cell.Range.Font.Size                 = 14;
                     cell.VerticalAlignment               = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                     cell.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                 }
             }
         }
         SaveFileDialog saveFileDialog1 = new SaveFileDialog();
         saveFileDialog1.Title            = "Сохранение doc файла";
         saveFileDialog1.Filter           = "doc файлы (*.doc)|*.doc|Все файлы (*.*)|*.*";
         saveFileDialog1.FilterIndex      = 1;
         saveFileDialog1.RestoreDirectory = true;
         if (saveFileDialog1.ShowDialog() == DialogResult.OK)
         {
             doc.SaveAs(string.Format(saveFileDialog1.FileName));
         }
         app.Quit();
         MessageBox.Show("Word-файл успешно сохранён", "GraduateDistribution");
     }
     catch (Exception gg)
     {
         MessageBox.Show(gg.Message, "Ошибка");
     }
 }
Ejemplo n.º 10
0
        public static void FillWordBookmarks(ref ActBase act)
        {
            var type = act.GetType();

            var application      = new Word.Application();
            var originalDocument = GetTemplateDoc(act, application);

            originalDocument.ActiveWindow.Selection.WholeStory();
            var newDocument = new Word.Document();

            newDocument.Range().FormattedText = originalDocument.Range().FormattedText;
            originalDocument.Close();

            var bookmarks = newDocument.Bookmarks;
            List <Word.Bookmark> bookMarks = new List <Word.Bookmark>();

            foreach (Word.Bookmark bookmark in bookmarks)
            {
                bookMarks.Add(bookmark);
            }

            var properties = type.GetProperties();
            var ok         = false;

            foreach (var propertyInfo in properties)
            {
                bool noUnderline = propertyInfo.Name.Contains("NoUnderline");
                var  propName    = propertyInfo.Name.Replace("NoUnderline", "");
                if (bookMarks.Exists(x => x.Name == propName))
                {
                    var        m     = bookMarks.First(x => x.Name == propName);
                    var        value = propertyInfo.GetValue(act);
                    Word.Range r;
                    if (value is string val)
                    {
                        if (noUnderline)
                        {
                            r = m.Range;
                            r.InsertAfter(val);
                        }
                        else
                        {
                            r = m.Range;
                            r.Delete(Word.WdUnits.wdCharacter, val.Length);
                            r.InsertAfter(val);
                            r.Underline = Word.WdUnderline.wdUnderlineSingle;
                        }
                    }
                    else if (value is DateTime date)
                    {
                        r = m.Range;
                        string dateStr = "";
                        if (propName.Contains("DateTime"))
                        {
                            dateStr = "\"" + date.ToString("dd") + "\"" + date.ToString(" MMMM yyyy HH:mm");
                        }
                        else if (propName.Contains("Time"))
                        {
                            dateStr = "\"" + date.ToString("HH") + "\" час. \"" + date.ToString("mm") + "\" мин.";
                        }
                        else if (propName.Contains("Date"))
                        {
                            dateStr = "\"" + date.ToString("dd") + "\"" + date.ToString(" MMMM yyyy");
                        }
                        r.Delete(Word.WdUnits.wdCharacter, dateStr.Length);
                        r.InsertAfter(dateStr);
                        r.Underline = Word.WdUnderline.wdUnderlineSingle;
                    }

                    ok = true;
                }
            }

            if (properties.Length > 0 && ok)
            {
                SaveAndCloseNewDocument(newDocument, ref act);
            }
            else
            {
                newDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
            }

            application.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            string finalHTML;
            List<string> listString = new List<string>();
            object True = true;
            Word.Application app = new Word.Application();
            Word.Document doc = new Word.Document();
            string fileName = @"D:\Programming\C#\Word To Markup Converter\hello world.docx";
            doc = app.Documents.Open(fileName, Type.Missing, True);

            //foreach (Word.Paragraph para in doc.Paragraphs)
            //{
            //    para.Range.Copy();
            //    stripClasses(Clipboard.GetText(TextDataFormat.Html));
            //}
            Word.ListParagraphs listpara = doc.ListParagraphs;
            IEnumerator ienum = doc.ListParagraphs.GetEnumerator();
            List<Tuple<string, Word.WdListType, int>> items = new List<Tuple<string, Word.WdListType, int>>();

            while (ienum.MoveNext())
            {
                Word.Range r = ((Word.Paragraph)ienum.Current).Range;
                items.Add(new  Tuple<string, Word.WdListType, int>(r.Text, r.ListFormat.ListType, r.ListFormat.ListLevelNumber));
            }

            items.Reverse();
            if (items.Count > 0)
            {
                listString = createList(items);
            }
            doc.SelectAllEditableRanges();
            doc.Range().Copy();

            string returnHTMLText = null;

            if (Clipboard.ContainsText(TextDataFormat.Html))
            {
                Console.WriteLine("html");
                returnHTMLText = Clipboard.GetText(TextDataFormat.Html);
                //Console.WriteLine(returnHTMLText);
                stripClasses(returnHTMLText, listString);

            }
            else
            {
                Console.WriteLine("no html");
                //Console.WriteLine(doc.);
                //returnHTMLText = Clipboard.GetText(TextDataFormat.Html);
            }

            doc.Close();
            app.Quit();
            Console.WriteLine("closed");
            while (true) ;
        }
Ejemplo n.º 12
0
        // Callback function for Keyboard hook.
        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                IntPtr active = GetForegroundWindow();
                if (!(active.Equals(self.MainWindowHandle) || active.Equals(GUIManager.GUIHandle)))
                {
                    inputStatus = KEYBOARD_IDLE;
                    GUIManager.disappear();
                }

                #region KeyCheck
                else
                {
                    currDoc = ThisAddIn.getCurrDocument();
                    int vkCode = Marshal.ReadInt32(lParam);

                    if (active.Equals(GUIManager.GUIHandle))
                    {
                        hotkeyTimer.Start();

                        int maxCount = tempList.Count - wrappedPage * REFERENCE_PER_PAGE - 1;

                        if (vkCode == KeyboardMapping.Keys["1"])
                        {
                            selectedItem = Math.Min(0, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["2"])
                        {
                            selectedItem = Math.Min(1, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["3"])
                        {
                            selectedItem = Math.Min(2, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["4"])
                        {
                            selectedItem = Math.Min(3, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["5"])
                        {
                            selectedItem = Math.Min(4, maxCount);
                        }
                        else if (vkCode == KeyboardMapping.Keys["VK_LEFT"])
                        {
                            if (wrappedPage > 0) wrappedPage -= 1;
                            selectedItem = 0;
                        }
                        else if (vkCode == KeyboardMapping.Keys["VK_RIGHT"])
                        {
                            if (wrappedPage < maxPage)
                            {
                                wrappedPage += 1;
                                selectedItem = 0;
                            }
                            else selectedItem = maxCount;
                        }

                        GUIManager.chooseItem(selectedItem, wrappedPage);
                    }

                    if (inputStatus == KEYBOARD_IDLE)
                    {
                        // Register place for starting typing.
                        inputStatus = KEYBOARD_TYPING;
                        Messenger.message("User is Typing!");
                        selStart = currDoc.Application.Selection.End;

                        //start Timer
                        resetTimer();
                    }
                    else if (inputStatus == KEYBOARD_TYPING)
                    {
                        resetTimer();
                    }
                    else if (inputStatus == KEYBOARD_PREFLISTSHOWED)
                    {
                        if (checkHotKey(vkCode, extendSentenceHotKey, 1))
                        {
                            string extending = tempList[wrappedPage * REFERENCE_PER_PAGE + selectedItem].getContent();

                            sentenceLength.Add(extending.Length);
                            int tempPos = selEnd;

                            // Print string
                            currDoc.Application.Selection.Start = selEnd;
                            currDoc.Application.Selection.End = selEnd;
                            currDoc.Application.Selection.TypeText(extending);

                            // Move cursor
                            selEnd = tempPos + extending.Length;
                            selStart = tempPos;
                            rng = currDoc.Range(selStart, selEnd);
                            rng.Select();

                            Messenger.message("Sentence Extended!");
                        }
                        else if (checkHotKey(vkCode, deleteSentenceHotKey, 4))
                        {
                            if (sentenceLength.Any())
                            {
                                int lastAdded = sentenceLength.Count - 1;
                                selStart = selEnd - sentenceLength[lastAdded];
                                rng = currDoc.Range(selStart, selEnd);
                                rng.Delete();
                                sentenceLength.RemoveAt(lastAdded);

                                if (sentenceLength.Any())
                                {
                                    lastAdded = sentenceLength.Count - 1;
                                    selEnd = selStart;
                                    selStart = selEnd - sentenceLength[lastAdded];
                                    rng = currDoc.Range(selStart, selEnd);
                                    rng.Select();
                                }
                                else
                                {
                                    selEnd = selStart;
                                    rng = currDoc.Range(selStart, selEnd);
                                    rng.Select();
                                }

                                Messenger.message("Sentence Reverted!");
                            }
                            else Messenger.message("Nothing extended yet!");
                        }
                        else if (vkCode == KeyboardMapping.Keys["SPACE"])
                        {
                            Messenger.message("KeyboardStatRestored!\n");

                            selStart = selEnd;
                            rng = currDoc.Range(selStart, selEnd);
                            rng.Select();

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

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

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

                    if (this.formValidate.ShowDialog() == DialogResult.OK)
                    {
                        /* Ocultamos la aplicacion durante los procesos de reemplazo y coloreado para hacer mas rapida la aplicacion */
                        Globals.ThisAddIn.Application.Visible = false;
                        waitForm = Waiting.Instance;
                        waitForm.Show();
                        /* Reemplzando texto original por el marcado */
                        /* Utilizando el rango de texto de la cita original y reemplzado el texto por el marcado */
                        int citaIndex = 0;
                        foreach (MarkupStruct cita in citas)
                        {
                            if (cita.Marked && cita.Colorized)
                            {
                                Clipboard.Clear();
                                cita.MarkedRtb.SelectAll();
                                Clipboard.SetText(cita.MarkedRtb.SelectedRtf, TextDataFormat.Rtf);
                                cita.RngCita.Paste();
                                cita.RngCita.Font.Size = 11;
                                Clipboard.Clear();
                            }
                            if (this.dtdType == "doc") {
                                if (citaIndex == 0)
                                    cita.RngCita.InsertBefore("[refs]");
                                if (citaIndex == (citas.Count - 1))
                                    cita.RngCita.InsertAfter("[/refs]");
                            }
                            citaIndex++;
                        }
                        /* Mostramos de nuevo la aplicacion */
                        waitForm.Hide();
                        Globals.ThisAddIn.Application.Visible = true;
                        /*Guardamos los cambios*/
                        if (!ActiveDocument.ReadOnly)
                        {
                            object FileName = Path.Combine(ActiveDocument.Path, ActiveDocument.Name);
                            object FileFormat = Word.WdSaveFormat.wdFormatFilteredHTML;
                            if (!ActiveDocument.Path.Contains(".htm"))
                                FileFormat = missing;
                            try
                            {
                                ActiveDocument.SaveAs(ref FileName, ref FileFormat, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing,
                                        ref missing, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing);
                            }catch (Exception e)
                            {
                                if (log.IsErrorEnabled) log.Error(e.Message);
                            }
                        }
                        else
                        {
                            MessageBox.Show(Resources.RegexMarkup_messageOnlyRead);
                        }
                    }
                }
            }
            if (log.IsInfoEnabled) log.Info("End");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.hasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Microsoft.Office.Interop.Word.Options   wdOptions      = null;
                Microsoft.Office.Interop.Word.Documents documents      = null;
                Microsoft.Office.Interop.Word.Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        Converter.releaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Microsoft.Office.Interop.Word.Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.releaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Microsoft.Office.Interop.Word.Window docWin     = null;
                    Microsoft.Office.Interop.Word.View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        docWinView.RevisionsView            = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments = false;
                    }
                    catch (SystemException) { }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        Converter.releaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        updateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    Converter.releaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    Converter.releaseCOMObject(docWinView);
                    Converter.releaseCOMObject(docWin);
                }

                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.resetValue(ref wdOptions);
                }

                Converter.releaseCOMObject(wdOptions);
                Converter.releaseCOMObject(documents);
                Converter.releaseCOMObject(doc);
                Converter.releaseCOMObject(tmpl);
                Converter.releaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    closeWordApplication(word);
                }
                Converter.releaseCOMObject(word);
            }
        }
Ejemplo n.º 15
0
        private Bitmap[] Scan4Word(string filePath)
        {
            //复制目标文件,后续将操作副本
            string tmpFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileName(filePath) + ".tmp";

            File.Copy(filePath, tmpFilePath);

            List <Bitmap> bmList = new List <Bitmap>();

            MSWord.ApplicationClass wordApplicationClass = new MSWord.ApplicationClass();
            wordApplicationClass.Visible = false;
            object missing = System.Reflection.Missing.Value;

            try
            {
                object readOnly       = false;
                object filePathObject = tmpFilePath;

                MSWord.Document document = wordApplicationClass.Documents.Open(ref filePathObject, 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);

                bool finished = false;
                while (!finished)
                {
                    document.Content.CopyAsPicture(); //拷贝到粘贴板
                    System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();
                    if (data.GetDataPresent(DataFormats.MetafilePict))
                    {
                        object   obj      = data.GetData(DataFormats.MetafilePict);
                        Metafile metafile = MetafileHelper.GetEnhMetafileOnClipboard(IntPtr.Zero); //从粘贴板获取数据
                        Bitmap   bm       = new Bitmap(metafile.Width, metafile.Height);
                        using (Graphics g = Graphics.FromImage(bm))
                        {
                            g.Clear(Color.White);
                            g.DrawImage(metafile, 0, 0, bm.Width, bm.Height);
                        }
                        bmList.Add(bm);
                        Clipboard.Clear();
                    }

                    object What       = MSWord.WdGoToItem.wdGoToPage;
                    object Which      = MSWord.WdGoToDirection.wdGoToFirst;
                    object startIndex = "1";
                    document.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref startIndex); // 转到下一页
                    MSWord.Range start = document.ActiveWindow.Selection.Paragraphs[1].Range;
                    MSWord.Range end   = start.GoToNext(MSWord.WdGoToItem.wdGoToPage);
                    finished = (start.Start == end.Start);
                    if (finished) //最后一页
                    {
                        end.Start = document.Content.End;
                    }

                    object oStart = start.Start;
                    object oEnd   = end.Start;
                    document.Range(ref oStart, ref oEnd).Delete(ref missing, ref missing); //处理完一页,就删除一页。
                }

                ((MSWord._Document)document).Close(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(document);

                return(bmList.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                wordApplicationClass.Quit(ref missing, ref missing, ref missing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplicationClass);
                File.Delete(tmpFilePath); //删除临时文件
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Метод создания и сохранения документов
        /// в форматах Microsoft Word (doc, PDF),
        /// Excel (exls)
        /// </summary>
        /// <param name="type">Тип создаваемого документа
        /// отчёт или статистика</param>
        /// <param name="format">Формат сохранения
        /// документ или таблица</param>
        /// <param name="name">Название документа</param>
        /// <param name="table">Входная таблица с данными</param>
        public void Document_Create(Document_Type type,
                                    Document_Format format, string name,
                                    DataTable table)
        {
            //Получение данных о конфигурации документа
            Configuration_class configuration_Class
                = new Configuration_class();

            configuration_Class.Document_Configuration_Get();
            //Проверка на пустоту названия
            switch (name != "" || name != null)
            {
            case true:
                //Выбор формата либо Word либо Excel
                switch (format)
                {
                case Document_Format.Word:
                    //Запуск процесса в дистпечере задач
                    word.Application application
                        = new word.Application();
                    //создание документа в процессе
                    word.Document document
                    //Присвоение документа процессу, Visible: true
                    //возможность редактирования документа
                        = application.Documents.Add(Visible: true);
                    try
                    {
                        //Объявление дипапазона для формирования текста
                        word.Range range = document.Range(0, 0);
                        //89Настройка отступов в документе
                        document.Sections.PageSetup.LeftMargin
                            = application.CentimetersToPoints(
                                  (float)Configuration_class.
                                  doc_Left_Merge);
                        document.Sections.PageSetup.TopMargin
                            = application.CentimetersToPoints(
                                  (float)Configuration_class.
                                  doc_Top_Merge);
                        document.Sections.PageSetup.RightMargin
                            = application.
                              CentimetersToPoints((float)
                                                  Configuration_class.doc_Right_Merg);
                        document.Sections.PageSetup.BottomMargin
                            = application.CentimetersToPoints(
                                  (float)Configuration_class.
                                  doc_Bottom_Merge);
                        //Присвоение текстового знеачения в дипазон
                        range.Text =
                            "Мвидео";
                        //Настройка выравнивания текста
                        range.ParagraphFormat.Alignment =
                            word.WdParagraphAlignment.
                            wdAlignParagraphCenter;
                        //Настройка интервала после абзаца
                        range.ParagraphFormat.SpaceAfter = 1;
                        //Настройка интервала перед абзаца
                        range.ParagraphFormat.SpaceBefore = 1;
                        //Настройка межстрочного интервала
                        range.ParagraphFormat.LineSpacingRule
                            = word.WdLineSpacing.wdLineSpaceSingle;
                        //Настройка названия шрифта
                        range.Font.Name = "Times New Roman";
                        //Настройка размера шрифта
                        range.Font.Size = 12;
                        //Добавление параграфов
                        document.Paragraphs.Add();        //В конце текста
                        document.Paragraphs.Add();        //Свободный
                        document.Paragraphs.Add();        //Для будущего текста
                        //Параграф для названия документа
                        word.Paragraph Document_Name
                            = document.Paragraphs.Add();
                        //Настройка параграфа через свойство диапазона
                        Document_Name.Format.Alignment
                            = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name = "Times New Roman";
                        Document_Name.Range.Font.Size = 16;
                        //Проверка на тип документа, отчёт или статистика
                        switch (type)
                        {
                        case Document_Type.Report:
                            Document_Name.Range.Text = "ОТЧЁТ";

                            break;

                        case Document_Type.Statistic:
                            Document_Name.Range.Text = "СТАТИСТИЧЕСКИЙ ОТЧЁТ";
                            break;
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        word.Paragraph statparg = document.Paragraphs.Add();
                        //Создание области таблицы в документе
                        word.Table stat_table
                        //Добавление таблицы в область документа
                        //Указывается параграф в котором документ создан
                        //Количество строк и столбцов
                            = document.Tables.Add(statparg.Range,
                                                  table.Rows.Count, table.Columns.Count);
                        //Настройка границ таблицы внутренние
                        stat_table.Borders.InsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Настройка границ таблицы внешние
                        stat_table.Borders.OutsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Выравнивание текста внутри ячеек по ширине
                        stat_table.Rows.Alignment
                            = word.WdRowAlignment.wdAlignRowCenter;
                        //Выравнивание текста внутри ячеек по высоте
                        stat_table.Range.Cells.VerticalAlignment =
                            word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size = 11;
                        stat_table.Range.Font.Name = "Times New Roman";
                        //Индексация столбцов и строк в Word начинается с 1,1
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text
                                    = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Парадграф с фиксациейц даты создания документа
                        word.Paragraph Footparg = document.Paragraphs.Add();
                        Footparg.Range.Text =
                            string.Format("Дата создания \t\t\t{0}",
                                          DateTime.Now.ToString("dd.MM.yyyy"));
                    }
                    catch (Exception ex)
                    {
                        System.Windows.Forms.MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        switch (format)
                        {
                        case Document_Format.Word:
                            //Сохранение документа с названием из метода,
                            //и в формате doc
                            document.SaveAs2(string.Format("{0}\\{1}", Environment.CurrentDirectory, name),
                                             word.WdSaveFormat.wdFormatDocument);
                            break;

                        case Document_Format.PDF:
                            //Сохранение документа в формате PDF
                            document.SaveAs2(string.Format("{0}\\{1}", Environment.CurrentDirectory, name),
                                             word.WdSaveFormat.wdFormatPDF);
                            break;
                        }
                        //Закрываем документ
                        document.Close();
                        //Выходим из процесса с его закрытием
                        application.Quit();
                    }
                    break;

                case Document_Format.Excel:
                    //Создание процесса Excel
                    excel.Application application_ex
                        = new excel.Application();
                    //Создание книги
                    excel.Workbook workbook
                        = application_ex.Workbooks.Add();
                    //Создание страницы
                    excel.Worksheet worksheet
                        = (excel.Worksheet)workbook.ActiveSheet;
                    try
                    {
                        switch (type)
                        {
                        case Document_Type.Report:
                            //Название страницы
                            worksheet.Name = "Отчёт";
                            for (int row = 0; row < table.Rows.Count; row++)
                            {
                                for (int col = 0; col < table.Columns.Count; col++)
                                {
                                    //ЗАнесение данных в ячейку
                                    worksheet.Cells[row + 1][col + 1]
                                        = table.Rows[row][col].ToString();
                                }
                            }
                            //Указание диапазона работы с ячеёками листа
                            excel.Range border
                            //Начало диапазона
                                = worksheet.Range[worksheet.Cells[1, 1],
                                                  //Динамический конец диапазона в зависимости от
                                                  //выдодимых данных
                                                  worksheet.Cells[table.Rows.Count + 1]
                                                  [table.Columns.Count + 1]];
                            //Стиль линий границ ячеек
                            border.Borders.LineStyle = excel.XlLineStyle.xlContinuous;
                            //Выравнивание во высоте
                            border.VerticalAlignment = excel.XlHAlign.xlHAlignCenter;
                            //Выравнивание по ширине
                            border.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                            //Внесение даты создания документа
                            worksheet.Cells[table.Rows.Count + 3][2]
                                = string.Format("Дата создания {0}",
                                                DateTime.Now.ToString());
                            //Объединение ячеек
                            worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2],
                                            worksheet.Cells[table.Rows.Count + 2,
                                                            table.Columns.Count + 2]].Merge();
                            break;

                        case Document_Type.Statistic:
                            worksheet.Name = "Статистический отчёт";
                            for (int row = 0; row < table.Rows.Count; row++)
                            {
                                for (int col = 0; col < table.Columns.Count; col++)
                                {
                                    worksheet.Cells[row + 1][col + 1]
                                        = table.Rows[row][col].ToString();
                                }
                            }
                            excel.Range border1
                                = worksheet.Range[worksheet.Cells[1, 1],
                                                  worksheet.Cells[table.Rows.Count + 1]
                                                  [table.Columns.Count + 1]];
                            border1.Borders.LineStyle
                                = excel.XlLineStyle.xlContinuous;
                            border1.VerticalAlignment
                                = excel.XlHAlign.xlHAlignCenter;
                            border1.HorizontalAlignment
                                = excel.XlHAlign.xlHAlignCenter;
                            worksheet.Cells[table.Rows.Count + 3][2]
                                = string.Format("Дата создания {0}",
                                                DateTime.Now.ToString());
                            worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2],
                                            worksheet.Cells[table.Rows.Count + 2,
                                                            table.Columns.Count + 2]].Merge();
                            //Класс области графиков
                            excel.ChartObjects chartObjects
                                = (excel.ChartObjects)worksheet.ChartObjects(
                                      Type.Missing);
                            //Область размещения графиков: отступы слева сверху,
                            //размер ширина и высота
                            excel.ChartObject chartObject
                                = chartObjects.Add(300, 50, 250, 250);
                            //Объявление области графика
                            excel.Chart chart = chartObject.Chart;
                            //Объявление колекции построений графиков
                            excel.SeriesCollection seriesCollection
                                = (excel.SeriesCollection)chart.SeriesCollection(
                                      Type.Missing);
                            //Объявление посторения графика
                            excel.Series series = seriesCollection.NewSeries();
                            //Тип графика
                            chart.ChartType = excel.XlChartType.xl3DColumn;
                            //Диапазон значений по оси X
                            series.XValues =
                                worksheet.get_Range("B2", "B" + table.Rows.Count + 1);
                            //Диапазон значений по оси Y
                            series.Values =
                                worksheet.get_Range("C2", "C" + table.Rows.Count + 1);
                            break;
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        //Сохранение книги
                        workbook.SaveAs(string.Format("{0}\\{1}", Environment.CurrentDirectory, name), application_ex.DefaultSaveFormat);
                        //Закрытие книги
                        workbook.Close();
                        //Завершение процесса
                        application_ex.Quit();
                    }
                    break;
                }
                break;

            case false:
                System.Windows.Forms.MessageBox.Show
                    ("Введите название документа");
                break;
            }
        }
Ejemplo n.º 17
0
        public SelectedPages(string inputFile, string outputTempFile, int start, int end, int total)
        {
            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            object oMissing = System.Reflection.Missing.Value;

            try
            {
                word.Visible = true;
                Object filename = inputFile;

                Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(ref filename, ref oMissing,
                                                                                 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                                 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                                 ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                word.Documents.Add();


                Range Selection = doc.Range();

                Selection.Start = Selection.GoTo(
                    What: WdGoToItem.wdGoToPage,
                    Which: WdGoToDirection.wdGoToFirst,
                    Count: start
                    ).Start;


                if (end == total)
                {
                    Selection.End = doc.Range().End;
                }
                else
                {
                    Selection.End = Selection.GoTo(
                        What: WdGoToItem.wdGoToPage,
                        Which: WdGoToDirection.wdGoToAbsolute,
                        Count: end + 1
                        ).Start - 1;
                }

                Selection.Copy();
                word.Selection.Paste();
                Clipboard.Clear();

                object outputFileName = outputTempFile;

                word.ActiveDocument.SaveAs(ref outputFileName,
                                           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);

                object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                word.Documents.Close(ref saveChanges, ref oMissing, ref oMissing);
                doc = null;
            }
            catch
            {
                if (File.Exists(outputTempFile))
                {
                    File.Delete(outputTempFile);
                }
                throw new Exception("Ocurrió un error durante el proceso de selección de páginas");
            }
            finally
            {
                ((_Application)word).Quit();
                word = null;
            }
        }
Ejemplo n.º 18
0
 private static void Replace(string search, string replace, ref Word.Document doc)
 {
     Word.Range r = doc.Range();
     r.Find.Execute(FindText: search, ReplaceWith: replace);
 }
Ejemplo n.º 19
0
        private void CopyBodyToMeeting(AppointmentItem ai, ref MeetingItem meetingItem)
        {
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem enter");
            Word.Document Doc = new Word.Document();
            Word.Document Doc2 = new Word.Document();
            //Word.Application App1;
            //Word.Selection Sel;

            Doc = ai.GetInspector.WordEditor as Word.Document;
            // Word.Application App2;
            // Word.Selection Sel2;

            if (Doc != null)
            {
                ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
                Doc.Activate();
                Doc.Select();
                //App1 = Doc.Windows.Application;
                //Sel = App1.Selection;
                //Sel.WholeStory();
                //Sel.Copy();
                Doc.Range().WholeStory();
                Doc.Range().Copy();

                Doc2 = meetingItem.GetInspector.WordEditor as Word.Document;
                if (Doc2 != null)
                {
                    Doc2.Activate();
                    object start = 0;
                    Range newRang = Doc2.Range(ref start, ref start);
                    int ioo = Doc2.Sections.Count;
                    Section sec = Doc2.Sections[1];

                    sec.Range.InsertBreak(Type.Missing);//插入换行符
                    try
                    {
                        //sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);
                        sec.Range.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting);
                        meetingItem.Save();
                        ThisAddIn.g_log.Info(string.Format("meetingItem doc length is {0}.", Doc2.Content.Text.Length));

                        if (meetingItem.Body == null || meetingItem.Body.Length < 100)
                        {
                            Doc2.Activate();
                            ((_Inspector)(meetingItem.GetInspector)).Activate();
                            ThisAddIn.g_log.Info("meetingItems's body is null Or body length is short,Activate over");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        ThisAddIn.g_log.Info("CopyBodyToMeeting comes Exception " + ex.ToString());
                    }
                }
                else
                {
                    ThisAddIn.g_log.Info("Doc is null");
                }
            }
            if (Doc != null)
            {
                Marshal.ReleaseComObject(Doc);
                Doc = null;
            }
            if (Doc2 != null)
            {
                Marshal.ReleaseComObject(Doc2);
                Doc2 = null;
            }
            //Doc = null;
            //Doc2 = null;
            ////App1 = null;
            ////Sel = null;
            ////            App2 = null;
            ////            Sel2 = null;

            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem exit");
        }
Ejemplo n.º 20
0
        private void GetBetterImg()
        {
            Range rangeAll = Globals.ThisAddIn.Application.ActiveDocument.Range();

            //range.SetRange(0,0);

            //while(range.End<rangeAll.End)
            //{
            //    range.Start = range.Start + 100;
            //    range.End = range.End + 100;
            //    Globals.ThisAddIn.Application.ActiveWindow.ScrollIntoView(range);
            //}



            object filename = @"D:\BaoProject\高分宝三期\2014届高三数学理科模拟试题(定稿).doc";  //文件保存路径
            Object Nothing  = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    WordDoc = WordApp.Documents.Add(ref filename, ref Nothing, ref Nothing, ref Nothing);


            Range range = WordDoc.Range(0, 500);



            range.Copy();



            rangeAll.Paste();

            rangeAll = Globals.ThisAddIn.Application.ActiveDocument.Range();

            rangeAll.SetRange(rangeAll.End, rangeAll.End);
            rangeAll.Select();

            System.Windows.Point pointend = CaretPos();

            rangeAll.SetRange(0, 0);
            rangeAll.Select();

            Microsoft.Office.Tools.Word.Document document = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument);
            Microsoft.Office.Tools.Word.DropDownListContentControl dropdown = document.Controls.AddDropDownListContentControl(rangeAll, "MyContentControl");
            dropdown.PlaceholderText = "My DropdownList Test";
            dropdown.DropDownListEntries.Add("Test01", "01", 1);
            dropdown.DropDownListEntries.Add("Test02", "02", 2);
            dropdown.DropDownListEntries.Add("Test03", "03", 3);

            rangeAll.SetRange(dropdown.Range.End + 1, dropdown.Range.End + 1);

            System.Drawing.Point o = new System.Drawing.Point(dropdown.Application.Left, dropdown.Application.Top);

            System.Drawing.Point o1 = this.PointToScreen(o);


            rangeAll.SetRange(0, 0);
            rangeAll.Select();

            System.Drawing.Point currentPos = GetPositionForShowing(Globals.ThisAddIn.Application.Selection);
            //Globals.ThisAddIn._FloatingPanel = new FloatingPanel(bookmark);



            rangeAll.Text = rangeAll.Text + "\n" + dropdown.Application.Top + "::::" + dropdown.Application.Left + "\n" + o1.X + "::::::" + o1.Y + "\n" + currentPos.X + "::::::" + currentPos.Y;


            Bitmap image = new Bitmap(currentPos.X, currentPos.Y);

            Graphics g = Graphics.FromImage(image);

            System.Drawing.Point FrmP = new System.Drawing.Point(currentPos.X, currentPos.Y);
            //ScreenP返回相对屏幕的坐标
            System.Drawing.Point ScreenP = this.PointToScreen(FrmP);

            g.CopyFromScreen(0, 0, 0, 0, image.Size);

            image.Save(@"C:\Users\Word\Desktop\3523433.png", System.Drawing.Imaging.ImageFormat.Png);

            int i = 0;
            //Image imgTemp = Metafile.FromStream(new MemoryStream(range.EnhMetaFileBits));

            //imgTemp.Save(@"C:\Users\Word\Desktop\1233.png", System.Drawing.Imaging.ImageFormat.Png);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Function which Marks all occurences of a particular word as Abbreviations or Acronyms
        /// </summary>
        public void AllOccurences()
        {
            DocumentProperties xmlparts = (DocumentProperties)currentDoc.CustomDocumentProperties;

            //If call is from Abbreviation button
            if (checkAbbrAcr)
            {
                object       missing  = System.Type.Missing;
                Object       startDoc = 0;
                Object       endDoc   = currentDoc.Characters.Count;
                MSword.Range rngDoc   = currentDoc.Range(ref startDoc, ref endDoc);
                MSword.Find  fndDoc   = rngDoc.Find;

                fndDoc.ClearFormatting();
                fndDoc.Forward = true;
                fndDoc.Text    = currentDoc.Application.Selection.Text.Trim();
                ExecuteFind(fndDoc);

                //Applying Abbreviation for all the occurrences of the selected Word
                while (fndDoc.Found)
                {
                    if (ValidateBookMark(rngDoc) == "Nobookmarks")
                    {
                        string nameAbbr = "Abbreviations" + GenerateId().ToString();
                        //Adding the Bookamrk for the selected Word
                        rngDoc.Bookmarks.Add(nameAbbr, ref missing);

                        object value = currentDoc.Application.Selection.Text.Trim() + "$#$" + tBx_MarkFullForm.Text.TrimEnd();
                        //Adding a custom property to the current document
                        xmlparts.Add(nameAbbr, false, type, value, System.Reflection.Missing.Value);
                    }
                    ExecuteFind(fndDoc);
                }
                this.Close();
            }
            else
            {
                object       missing  = System.Type.Missing;
                Object       startDoc = 0;
                Object       endDoc   = currentDoc.Characters.Count;
                MSword.Range rngDoc   = currentDoc.Range(ref startDoc, ref endDoc);
                MSword.Find  fndDoc   = rngDoc.Find;

                fndDoc.ClearFormatting();
                fndDoc.Forward = true;
                fndDoc.Text    = currentDoc.Application.Selection.Text.Trim();
                ExecuteFind(fndDoc);

                //Applying Acronymns for all the occurrences of the selected Word
                while (fndDoc.Found)
                {
                    if (ValidateBookMark(rngDoc) == "Nobookmarks")
                    {
                        String nameAcr = "Acronyms" + pronounceAbbrAcr + GenerateId().ToString();
                        //Adding the Bookamrk for the selected Word
                        rngDoc.Bookmarks.Add(nameAcr, ref missing);

                        object value = currentDoc.Application.Selection.Text.Trim() + "$#$" + tBx_MarkFullForm.Text.TrimEnd();
                        //Adding a custom property to the current document
                        xmlparts.Add(nameAcr, false, type, value, System.Reflection.Missing.Value);
                    }
                    ExecuteFind(fndDoc);
                }
                this.Close();
            }
        }
        //Сохранение в файл
        public static void CreatingWordList(string fileName, List <Publication> filterPublications, int type)
        {
            Word.Application wordApp = new Word.Application();
            wordApp.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            Word.Document wordDoc = new Word.Document();
            wordDoc = wordApp.Documents.Add();

            object endOfDoc = "\\endofdoc";

            for (int i = 0, fbCnt = filterPublications.Count; i < fbCnt; i++)
            {
                string authors = "";
                string editors = "";
                string info = "";
                string pages = "";
                int    start = 0, end = 0;

                var item = filterPublications[i];

                if (type == 1)
                {
                    //Попытка вычисления кол-ва страниц
                    try
                    {
                        string[] endStart = item.pages.Split(new string[] { " - " }, StringSplitOptions.None);
                        pages = (int.Parse(endStart[1]) - int.Parse(endStart[0])).ToString();
                    }
                    catch
                    {
                        pages = item.pages;
                    }

                    //Формирование строки
                    //Авторов от 1 до 3 включительно
                    if (item.authors.Count <= 3)
                    {
                        for (int j = 0, authCnt = item.authors.Count; j < authCnt; j++)
                        {
                            if (j != authCnt - 1)
                            {
                                authors += item.authors[j] + ", ";
                            }
                            else
                            {
                                authors += item.authors[j];
                            }
                        }
                        //Для книги
                        if (item.isbn != "")
                        {
                            info = item.authors[0] + ". " + item.booktitle +
                                   " : " + item.title + " / " + authors + ". – " + item.publisher + ", " +
                                   item.year + ". – " + pages + " p.";
                        }
                        //Для других типов
                        else
                        {
                            info = item.authors[0] + ". " + item.title +
                                   " / " + authors + " // " + item.journal + ". – " + item.year + ". – Vol. " + item.volume
                                   + ". – P. " + item.pages + ".";
                        }
                    }
                    //Авторов больше 3
                    else
                    {
                        authors = item.authors[0] + " [et al.]";
                        //Для книг
                        if (item.isbn != "")
                        {
                            info = item.booktitle + " : " + item.title + " / " +
                                   authors + ". – " + item.publisher + ", " + item.year + ". – " + pages + " p.";
                        }
                        else
                        {
                            info = item.title + " / " + authors + " // " + item.journal +
                                   ". - " + item.year + ". – Vol. " + item.volume + ". – P. " + item.pages + ".";
                        }
                    }
                }
                else
                {
                    if (item.authors.Count == 1)
                    {
                        authors = item.authors[0] + ", ";
                    }
                    else
                    {
                        for (int j = 0; j < item.authors.Count; j++)
                        {
                            if (j != item.authors.Count - 2)
                            {
                                authors += item.authors[j] + ", ";
                            }
                            else
                            {
                                authors += item.authors[j] + " and " + item.authors[j + 1] + ", ";
                                break;
                            }
                        }
                    }

                    if (item.editor.Count == 1)
                    {
                        editors = item.editor[0] + ", Ed., ";
                    }
                    else
                    {
                        for (int j = 0; j < item.editor.Count; j++)
                        {
                            if (j != item.editor.Count - 2)
                            {
                                editors += item.editor[j] + ", ";
                            }
                            else
                            {
                                editors += item.editor[j] + " and " + item.editor[j + 1] + ", Eds., ";
                                break;
                            }
                        }
                    }

                    bool   flag      = false;
                    string edAuthors = authors;
                    if (new HashSet <string>(item.authors).SetEquals(item.editor))
                    {
                        if (item.authors.Count == 1)
                        {
                            edAuthors += " Ed., ";
                        }
                        else
                        {
                            edAuthors += " Eds., ";
                        }
                        flag = true;
                    }

                    start = edAuthors.Length + 7 + item.title.Length;
                    //Если книга
                    if (item.isbn != "")
                    {
                        if (!flag)
                        {
                            info = edAuthors + "\"" + item.title + ",\" in " + item.booktitle + ", " + editors +
                                   item.publisher + ", " + item.year + ", pp. " + item.pages + ".";
                        }
                        else
                        {
                            info = edAuthors + "\"" + item.title + ",\" in " + item.booktitle + ", " +
                                   item.publisher + ", " + item.year + ", pp. " + item.pages + ".";
                        }
                        end = start + item.booktitle.Length + 1;
                    }
                    //Другие варианты
                    else
                    {
                        info = authors + "\"" + item.title + ",\" in " + item.journal + ", " +
                               item.year + ", vol. " + item.volume + ", pp. " + item.pages + ", doi: " + item.doi + ".";
                        end = start + item.journal.Length + 1;
                    }
                }

                //Запись строки в файл
                Word.Paragraph paragraph;
                paragraph            = wordDoc.Content.Paragraphs.Add();
                paragraph.Range.Text = info;
                if (type == 2)
                {
                    object     oStart = paragraph.Range.Start + start;
                    object     oEnd   = paragraph.Range.Start + end;
                    Word.Range rBold  = wordDoc.Range(ref oStart, ref oEnd);
                    rBold.Italic = 1;
                }
                paragraph.Range.Font.Size = 14;
                paragraph.Range.Font.Name = "Times New Roman";

                if (i == 0)
                {
                    paragraph.Range.ListFormat.ApplyNumberDefault(Word.WdListGalleryType.wdNumberGallery);
                }
                if (i != fbCnt - 1)
                {
                    paragraph.Range.InsertParagraphAfter();
                }
            }

            //Сохранение Word
            DialogResult dialogResult = DialogResult.No;

            try
            {
                wordDoc.SaveAs2(fileName);
                dialogResult = MessageBox.Show("Сохранение прошло успешно\nОткрыть файл?", "Science Direct Systematizer",
                                               MessageBoxButtons.YesNo);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при сохранении.\nФайл не сохранен.\n" + ex.Message.ToString(),
                                "Science Direct Systematizer");
            }

            if (dialogResult == DialogResult.Yes)
            {
                wordApp.Visible = true;
                wordApp.Activate();
                wordApp.WindowState = Word.WdWindowState.wdWindowStateMaximize;
            }
            else
            {
                wordApp.Quit();
            }
        }
Ejemplo n.º 23
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.º 24
0
        private void Button2_Click(object sender, EventArgs e)
        {
            int            GetTblIndex    = 0;
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = ".docx|*.docx";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //File.SetAttributes(openFileDialog.FileName, FileAttributes.);
                direct      = openFileDialog.FileName;
                label4.Text = direct.Split('\\').Last();
            }
            Object missing     = System.Reflection.Missing.Value;
            Object confConv    = false;
            Object readOnly    = false;
            Object isVisible   = false;
            Object saveChanges = false;
            Object filename    = direct;

            _Word.Application word = new _Word.Application();
            _Word.Document    doc  = new _Word.Document();
            doc          = word.Documents.Open(ref filename, ref confConv, ref readOnly);
            word.Visible = false;
            _Word.Tables tbl = doc.Tables;
            for (int i = 1; i < tbl.Count + 1; i++)
            {
                _Word.Range range = tbl[i].Cell(1, 2).Range;
                if (range.Text.Substring(0, 27) == "Наименование разделов и тем")
                {
                    //MessageBox.Show("ALL RIGHT");
                    GetTblIndex = i;
                    break;
                }
            }
            int idList = 0;

            object begCell1 = tbl[GetTblIndex].Cell(1, 4).Range.Start;
            object endCell1 = tbl[GetTblIndex].Cell(2, 5).Range.End;

            _Word.Range ranga = doc.Range(ref begCell1, ref endCell1);
            ranga.Select();
            word.Selection.Cells.Merge();
            //word.Visible = true;
            begCell1 = tbl[GetTblIndex].Cell(2, 2).Range.Start;
            //MessageBox.Show(tbl[GetTblIndex].Cell(2, 2).Range.Text);
            int RowsCount = 0;

            foreach (_Word.Row r in tbl[GetTblIndex].Rows)
            {
                if (r.Cells[2].Range.Text.Substring(0, 4) != "Тема" && RowsCount > 0)
                {
                    break;
                }
                RowsCount++;
            }
            endCell1 = tbl[GetTblIndex].Cell(RowsCount, 6).Range.End;
            //MessageBox.Show(tbl[GetTblIndex].Cell(5, 6).Range.Text);
            _Word.Range CutTbl = doc.Range(ref begCell1, ref endCell1);
            foreach (_Word.Row row in CutTbl.Rows)
            {
                if (row.Cells[2].Range.Text.Substring(0, 4) == "Тема")
                {
                    AllListLec.Add(row.Cells[4].Range.Text.Replace("\a", "").Replace("\r", "") + ";" + row.Cells[2].Range.Text.Replace("\a", "").Replace("\r", ""));
                    AllListPr.Add(row.Cells[5].Range.Text.Replace("\a", "").Replace("\r", "") + ";" + row.Cells[2].Range.Text.Replace("\a", "").Replace("\r", ""));
                    NameOfTheme.Add(row.Cells[2].Range.Text.Replace("\a", "").Replace("\r", ""));
                }
                idList++;
            }
            doc.Close(ref saveChanges);
            word.Quit(ref saveChanges);
        }
Ejemplo n.º 25
0
        private object G_str_path;                         //定義文件儲存路徑欄位

        private void btn_New_Click(object sender, EventArgs e)
        {
            btn_New.Enabled = false;                                 //停用新建按鈕
            ThreadPool.QueueUserWorkItem(                            //開始線程池
                (pp) =>                                              //使用lambda表達式
            {
                G_wa               = new Word.Application();         //建立應用程式對像
                object P_obj       = "Normal.dot";                   //定義文檔模板
                Word.Document P_wd = G_wa.Documents.Add();
                Word.Range P_Range = P_wd.Range(                     //得到文檔範圍
                    ref G_missing, ref G_missing);
                DataTier P_DataTier = new DataTier();                //建立資料層對像
                List <InstanceClass> P_List_InstanceClass            //得到資料集合
                          = P_DataTier.GetMessage();
                object o1 = Word.WdDefaultTableBehavior.             //設定文檔中表格格式
                            wdWord8TableBehavior;
                object o2 = Word.WdAutoFitBehavior.                  //設定文檔中表格格式
                            wdAutoFitWindow;
                Word.Table P_WordTable = P_Range.Tables.Add(P_Range, //在文檔中新增表格
                                                            P_List_InstanceClass.Count + 2, 5, ref o1, ref o2);
                P_WordTable.Cell(1, 1).Range.Text = "ID";            //向表格中新增訊息
                P_WordTable.Cell(1, 2).Range.Text = "姓名";            //向表格中新增訊息
                P_WordTable.Cell(1, 3).Range.Text = "語文成績";          //向表格中新增訊息
                P_WordTable.Cell(1, 4).Range.Text = "數學成績";          //向表格中新增訊息
                P_WordTable.Cell(1, 5).Range.Text = "英語成績";          //向表格中新增訊息
                for (int i = 2; i < P_List_InstanceClass.Count + 2; i++)
                {
                    P_WordTable.Cell(i, 1).Range.Text =    //向表格中新增訊息
                                                        P_List_InstanceClass[i - 2].id.ToString();
                    P_WordTable.Cell(i, 2).Range.Text =    //向表格中新增訊息
                                                        P_List_InstanceClass[i - 2].Name;
                    P_WordTable.Cell(i, 3).Range.Text =    //向表格中新增訊息
                                                        P_List_InstanceClass[i - 2].Chinese.ToString();
                    P_WordTable.Cell(i, 4).Range.Text =    //向表格中新增訊息
                                                        P_List_InstanceClass[i - 2].Math.ToString();
                    P_WordTable.Cell(i, 5).Range.Text =    //向表格中新增訊息
                                                        P_List_InstanceClass[i - 2].English.ToString();
                }
                float P_Chinese = 0;                                 //定義變數用於計算資料列
                float P_Math    = 0;                                 //定義變數用於計算資料列
                float P_English = 0;                                 //定義變數用於計算資料列
                P_List_InstanceClass.
                ForEach((Instance) =>                                //使用Lambda表達式
                {
                    P_Chinese += ((InstanceClass)Instance).Chinese;  //計算資料列
                    P_Math    += ((InstanceClass)Instance).Math;     //計算資料列
                    P_English += ((InstanceClass)Instance).English;  //計算資料列
                });
                P_WordTable.Cell(P_List_InstanceClass.Count + 2,     //向表格中新增訊息
                                 1).Range.Text = "科目總成績";
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 3). //向表格中新增訊息
                Range.Text = P_Chinese.ToString();
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 4). //向表格中新增訊息
                Range.Text = P_Math.ToString();
                P_WordTable.Cell(P_List_InstanceClass.Count + 2, 5). //向表格中新增訊息
                Range.Text = P_English.ToString();
                G_str_path = string.Format(                          //計算文件儲存路徑
                    @"{0}\{1}", G_FolderBrowserDialog.SelectedPath,
                    DateTime.Now.ToString("yyyy年M月d日h時s分m秒fff毫秒") + ".doc");
                P_wd.SaveAs(    //儲存Word文件
                    ref G_str_path,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                    ref G_missing, ref G_missing, ref G_missing);
                ((Word._Application)G_wa.Application).Quit( //退出應用程式
                    ref G_missing, ref G_missing, ref G_missing);
                this.Invoke(                                //呼叫視窗線程
                    (MethodInvoker)(() =>                   //使用lambda表達式
                {
                    MessageBox.Show(                        //彈出消息對話框
                        "成功建立Word文檔!", "提示!");
                    btn_display.Enabled = true;             //啟用顯示按鈕
                }));
            });
        }
Ejemplo n.º 26
0
        private void btn_OutPut_Click(object sender, EventArgs e)
        {
            List <Fruit> P_Fruit = new List <Fruit>();//建立資料集合

            foreach (DataGridViewRow dgvr in dgv_Message.Rows)
            {
                P_Fruit.Add(new Fruit()//向資料集合新增資料
                {
                    Name  = dgvr.Cells[0].Value.ToString(),
                    Price = Convert.ToSingle(dgvr.Cells[1].Value.ToString())
                });
            }
            SaveFileDialog P_SaveFileDialog =//建立儲存文件對話框物件
                                              new SaveFileDialog();

            P_SaveFileDialog.Filter = "*.doc|*.doc";
            if (DialogResult.OK ==//確認是否儲存文件
                P_SaveFileDialog.ShowDialog())
            {
                ThreadPool.QueueUserWorkItem(                                             //開始線程池
                    (pp) =>                                                               //使用lambda表達式
                {
                    G_wa               = new Microsoft.Office.Interop.Word.Application(); //建立應用程式物件
                    object P_obj       = "Normal.dot";                                    //定義文檔模板
                    Word.Document P_wd = G_wa.Documents.Add(                              //向Word應用程式中新增文檔
                        ref P_obj, ref G_missing, ref G_missing, ref G_missing);
                    Word.Range P_Range = P_wd.Range(                                      //得到文檔範圍
                        ref G_missing, ref G_missing);
                    object o1 = Word.WdDefaultTableBehavior.                              //設定文檔中表格格式
                                wdWord8TableBehavior;
                    object o2 = Word.WdAutoFitBehavior.                                   //設定文檔中表格格式
                                wdAutoFitWindow;
                    Word.Table P_WordTable = P_Range.Tables.Add(P_Range,                  //在文檔中新增表格
                                                                P_Fruit.Count, 2, ref o1, ref o2);
                    P_WordTable.Cell(1, 1).Range.Text = "水果";                             //向表格中新增訊息
                    P_WordTable.Cell(1, 2).Range.Text = "價格";                             //向表格中新增訊息
                    for (int i = 2; i < P_Fruit.Count + 1; i++)
                    {
                        P_WordTable.Cell(i, 1).Range.Text = //向表格中新增訊息
                                                            P_Fruit[i - 2].Name;
                        P_WordTable.Cell(i, 2).Range.Text = //向表格中新增訊息
                                                            P_Fruit[i - 2].Price.ToString();
                    }
                    object P_Path = P_SaveFileDialog.FileName;
                    P_wd.SaveAs(//儲存Word文件
                        ref P_Path,
                        ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                        ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                        ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                        ref G_missing, ref G_missing, ref G_missing);
                    ((Word._Application)G_wa.Application).Quit( //退出應用程式
                        ref G_missing, ref G_missing, ref G_missing);
                    this.Invoke(                                //呼叫視窗線程
                        (MethodInvoker)(() =>                   //使用lambda表達式
                    {
                        MessageBox.Show(                        //彈出消息對話框
                            "成功建立Word文檔!", "提示!");
                    }));
                });
            }
        }
Ejemplo n.º 27
0
        private void HighlightText(object fileName, List <String> textToFind)
        {
            path = tbFile.Text;
            //object fileName = path;
            //textToFind = "test";
            object readOnly = false;

            Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document    doc  = new Microsoft.Office.Interop.Word.Document();
            object missing = Type.Missing;

            try
            {
                doc = word.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);
                doc.Activate();


                object matchPhrase       = false;
                object matchCase         = false;
                object matchPrefix       = false;
                object matchSuffix       = false;
                object matchWholeWord    = false;
                object matchWildcards    = false;
                object matchSoundsLike   = false;
                object matchAllWordForms = false;
                object matchByte         = false;
                object ignoreSpace       = false;
                object ignorePunct       = false;

                object highlightedColor = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
                object textColor        = Microsoft.Office.Interop.Word.WdColor.wdColorLightOrange;

                Microsoft.Office.Interop.Word.Range range = doc.Range();
                foreach (object c in textToFind)
                {
                    bool highlighted = range.Find.HitHighlight(c,
                                                               highlightedColor,
                                                               textColor,
                                                               matchCase,
                                                               matchWholeWord,
                                                               matchPrefix,
                                                               matchSuffix,
                                                               matchPhrase,
                                                               matchWildcards,
                                                               matchSoundsLike,
                                                               matchAllWordForms,
                                                               matchByte,
                                                               false,
                                                               false,
                                                               false,
                                                               false,
                                                               false,
                                                               ignoreSpace,
                                                               ignorePunct,
                                                               false);
                }
                System.Diagnostics.Process.Start(fileName.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error : " + ex.Message);
                Console.ReadKey(true);
            }
        }
Ejemplo n.º 28
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var t = e.Argument as Tuple <string, string, string, string>;

            if (String.IsNullOrWhiteSpace(t.Item2) || String.IsNullOrWhiteSpace(t.Item3)) //вставить проверку, что указаны годы
            {
                MessageBox.Show("Не указаны годы рождения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (t.Item1 == "")
            {
                MessageBox.Show("Район не задан!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            string select = @"SELECT     Student.name, Student.birth, city.city, Student.street, Student.house, Student.flat, district.district
                                FROM         Student INNER JOIN
                                city ON Student.id_city = city.id INNER JOIN
                                district ON Student.id_district = district.id
                                WHERE id_district = " + ConvertDistrictNameToIdDistrict(t.Item1) +
                            @" AND (prikazNumKval = '') AND (prikazNumOut = '') 
                                   AND (birth >= '01.01." + t.Item2 + "' AND birth <= '31.12." + t.Item3 + @"')
                                ORDER BY name";

            DataSet ds1 = new DataSet();

            try
            {
                ds1 = Util.FillTable("Student", select);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.ToString());
            }

            if (ds1.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("С указанными данными никого нет!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            Word.Application wdApp  = new Word.Application();
            Word.Document    wdDoc  = new Word.Document();
            Object           wdMiss = System.Reflection.Missing.Value;

            wdDoc = wdApp.Documents.Add(ref wdMiss, ref wdMiss, ref wdMiss, ref wdMiss);
            //wdApp.Visible = true; //сначала формируется документ, показывать потом
            wdDoc.PageSetup.LeftMargin   = 40;
            wdDoc.PageSetup.RightMargin  = 25;
            wdDoc.PageSetup.TopMargin    = 20;
            wdDoc.PageSetup.BottomMargin = 20;
            Word.Table tb;
            Word.Range _range;

            int columnsCount = 5;

            tb = wdDoc.Tables.Add(wdApp.Selection.Range, ds1.Tables[0].Rows.Count + 3, columnsCount);
            tb.Columns[1].Width = 40;
            tb.Rows[1].Height   = 40;
            tb.Columns[2].Width = 210;
            tb.Rows[2].Height   = 40;
            tb.Columns[3].Width = 60;
            tb.Rows[3].Height   = 40;
            tb.Columns[4].Width = 140;
            tb.Columns[5].Width = 90;

            Word.Row  row       = tb.Rows[1];
            Word.Cell firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }
            row       = tb.Rows[2];
            firstCell = row.Cells[1];
            foreach (Word.Cell currCell in row.Cells)
            {
                if (currCell.ColumnIndex != firstCell.ColumnIndex)
                {
                    firstCell.Merge(currCell);
                }
            }

            tb.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb.Cell(1, 1).Select();
            wdApp.Selection.Range.Font.Size = 14;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(1, 1).Range.Text        = "Список";
            tb.Rows[2].Select();
            wdApp.Selection.Range.Font.Size = 12;
            wdApp.Selection.Font.Bold       = 1;
            tb.Cell(2, 1).Range.Text        = " студентов " + t.Item2 + " - " + t.Item3 +
                                              " г.р. проживающих в " + DistrictForm(t.Item1) + " районе на " + t.Item4 + " года ";

            tb.Rows[3].Select();
            wdApp.Selection.Font.Bold = 1;
            tb.Cell(3, 1).Range.Text  = "№ п/п";
            tb.Cell(3, 2).Range.Text  = "ФИО";
            tb.Cell(3, 3).Range.Text  = "Дата рождения";
            tb.Cell(3, 4).Range.Text  = "Домашний адрес";
            tb.Cell(3, 5).Range.Text  = "Примечание";


            int rowCount  = 3;
            int rowNumber = 0;

            foreach (DataRow str in ds1.Tables[0].Rows)
            {
                rowCount++;
                rowNumber++;
                tb.Cell(rowCount, 1).Range.Text = rowNumber.ToString() + ".";
                tb.Cell(rowCount, 2).Range.Text = str.ItemArray[0].ToString();
                tb.Cell(rowCount, 3).Range.Text = DateTime.Parse(str.ItemArray[1].ToString()).ToShortDateString(); //номер курса считать
                tb.Cell(rowCount, 4).Range.Text = "г." + str.ItemArray[2].ToString() + ", ул." + str.ItemArray[3].ToString() + ", д." +
                                                  str.ItemArray[4].ToString() + ", кв." + str.ItemArray[5].ToString();
            }

            _range = wdDoc.Range(tb.Cell(4, 2).Range.Start, tb.Cell(rowCount, 5).Range.End);
            _range.Select();
            wdApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            _range = wdDoc.Range(tb.Cell(3, 1).Range.Start, tb.Cell(rowCount, columnsCount).Range.End);
            _range.Select();

            /* вызов макроса для отображения границ таблицы
             * Sub Сетка()
             * 'Сетка макрос
             * With Selection.Borders(wdBorderTop)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderLeft)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderBottom)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderRight)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderHorizontal)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * With Selection.Borders(wdBorderVertical)
             * .LineStyle = Options.DefaultBorderLineStyle
             * .LineWidth = Options.DefaultBorderLineWidth
             * .Color = Options.DefaultBorderColor
             * End With
             * End Sub
             */
            try
            {
                wdApp.Run("Сетка");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " Сетка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }


            //таблица для подписей
            wdApp.Selection.EndOf(Word.WdUnits.wdStory);
            wdApp.Selection.InsertBreak(10);

            Word.Table tb2;
            tb2 = wdDoc.Tables.Add(wdApp.Selection.Range, 2, 4);

            tb2.Columns[1].Width = 40;
            tb2.Columns[2].Width = 180;
            tb2.Columns[3].Width = 180;

            tb2.Select();
            wdApp.Selection.ParagraphFormat.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wdApp.Selection.Range.Font.Name            = "Times New Roman";
            wdApp.Selection.Range.Font.Size            = 10;
            wdApp.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            wdApp.Selection.ParagraphFormat.SpaceAfter = 0;

            tb2.Rows[1].Select();
            tb2.Cell(1, 2).Range.Text = "Директор колледжа";
            tb2.Cell(1, 4).Range.Text = " ";

            tb2.Rows[2].Select();
            tb2.Cell(2, 2).Range.Text = " ";
            tb2.Cell(2, 3).Range.Text = " ";

            //нумерация страниц
            Word.Window activeWindow = wdDoc.Application.ActiveWindow;
            object      currentPage  = Word.WdFieldType.wdFieldPage;
            object      totalPages   = Word.WdFieldType.wdFieldNumPages;

            //переход к редактированию футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            activeWindow.ActivePane.Selection.Paragraphs.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //напечатает номер страницы в формате X стр. из Y
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref currentPage, ref wdMiss, ref wdMiss);
            activeWindow.Selection.TypeText(" стр. из ");
            activeWindow.Selection.Fields.Add(activeWindow.Selection.Range, ref totalPages, ref wdMiss, ref wdMiss);
            //выход из футера
            activeWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

            wdApp.Visible = true; //показать документ пользователю
        }
Ejemplo n.º 29
0
        private void CopyBodyToMeeting(AppointmentItem ai, ref MeetingItem meetingItem)
        {
            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem enter");
            Word.Document Doc = new Word.Document();
            Word.Document Doc2 = new Word.Document();
            Word.Application App1;
            Word.Selection Sel;

            Doc = ai.GetInspector.WordEditor as Word.Document;

            if (Doc != null)
            {
                ThisAddIn.g_log.Info(string.Format("appointmentItem doc length is {0}.", Doc.Content.Text.Length));
                Doc.Activate();
                Doc.Select();
                App1 = Doc.Windows.Application;
                Sel = App1.Selection;
                Sel.WholeStory();
                Sel.Copy();

                Doc2 = meetingItem.GetInspector.WordEditor as Word.Document;
                if (Doc2 != null)
                {
                    Doc2.Activate();
                    object start = 0;
                    Range newRang = Doc2.Range(ref start, ref start);

                    int ioo = Doc2.Sections.Count;
                    Section sec = Doc2.Sections[1];

                    sec.Range.InsertBreak(Type.Missing);//插入换行符
                    sec.Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);

                    meetingItem.Save();
                    ThisAddIn.g_log.Info(string.Format("meetingItem doc length is {0}.", Doc2.Content.Text.Length));
                    //ThisAddIn.g_log.Info(string.Format("mailItem body length is {0}.", meetingItem.Body.Length));

                    if (meetingItem.Body == null || meetingItem.Body.Length < 100)
                    {
                        Doc2.Activate();
                        ((_Inspector)(meetingItem.GetInspector)).Activate();
                    }
                }
            }
            Doc = null;
            Doc2 = null;
            App1 = null;
            Sel = null;

            ThisAddIn.g_log.Info("Copy AppointmentItem body to MeetingItem exit");
        }
Ejemplo n.º 30
0
    /// <summary>
    /// Creates a temporary Word App in order to add an OLE Object, get's the OpenXML data from the file (similar to the Code Reflector info)
    /// </summary>
    private void SetupOleFileInformation()
    {
        Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();

        Microsoft.Office.Interop.Word.Document wordDocument = wordApplication.Documents.Add(ref _objectMissing, ref _objectMissing,
                                                                                            ref _objectMissing, ref _objectMissing);
        object iconObjectFileName = _objectMissing;
        object objectClassType    = FileType;
        object objectFilename     = _fileInfo.ToString();

        Microsoft.Office.Interop.Word.InlineShape inlineShape = null;
        if (_displayAsIcon)
        {
            if (ObjectIcon != null)
            {
                using (FileStream iconStream = new FileStream(ObjectIconFile, FileMode.Create))
                {
                    ObjectIcon.Save(iconStream);
                    iconObjectFileName = ObjectIconFile;
                }
            }
            object objectIconLabel = _fileInfo.Name;
            inlineShape = wordDocument.InlineShapes.AddOLEObject(ref objectClassType,
                                                                 ref objectFilename, ref _objectFalse, ref _objectTrue, ref iconObjectFileName,
                                                                 ref _objectMissing, ref objectIconLabel, ref _objectMissing);
        }
        else
        {
            try
            {
                Image image = Image.FromFile(_fileInfo.ToString());
                _objectIsPicture = true;
                OleImageStyle    = String.Format("height:{0}pt;width:{1}pt", image.Height, image.Width);
                wordDocument.InlineShapes.AddPicture(_fileInfo.ToString(), ref _objectMissing, ref _objectTrue, ref _objectMissing);
            }
            catch
            {
                inlineShape = wordDocument.InlineShapes.AddOLEObject(ref objectClassType,
                                                                     ref objectFilename, ref _objectFalse, ref _objectFalse, ref _objectMissing, ref _objectMissing,
                                                                     ref _objectMissing, ref _objectMissing);
            }
        }
        WordOpenXml = wordDocument.Range(ref _objectMissing, ref _objectMissing).WordOpenXML;
        if (_objectIsPicture)
        {
            OleObjectBinaryData = GetPictureBinaryData();
            OleImageBinaryData  = GetPictureBinaryData();
        }
        else
        {
            OleObjectBinaryData = GetOleBinaryData(_oleObjectDataTag);
            OleImageBinaryData  = GetOleBinaryData(_oleImageDataTag);
        }
        // Not sure why, but Excel seems to hang in the processes if you attach an Excel file…
        // This kills the excel process that has been started < 15 seconds ago (so not to kill the user's other Excel processes that may be open)
        if (FileType.StartsWith("Excel"))
        {
            Process[] processes = Process.GetProcessesByName("EXCEL");
            foreach (Process process in processes)
            {
                if (DateTime.Now.Subtract(process.StartTime).Seconds <= 15)
                {
                    process.Kill();
                    break;
                }
            }
        }
        wordDocument.Close(ref _objectFalse, ref _objectMissing, ref _objectMissing);
        wordApplication.Quit(ref _objectMissing, ref _objectMissing, ref _objectMissing);
    }
Ejemplo n.º 31
0
        private void createWords()
        {
            int filesToCreateTemp = frm1.filesToCreate;             // avoid change in '#files to be created' during runtime

            try
            {
                string workingDir = frm1.workingDirectory + "officeSimulation_word\\";
                System.IO.Directory.CreateDirectory(workingDir);
                int    documentCount    = 0;
                string wordFileNameDate = frm1.wordFileName + DateTime.Now.ToString("dd-MM-yyyy_HH-mm");
                string wordFileNameDateFinal;

                // ~~~~~~~~~~~~~~~~~~~~~~~~~~ Word instance ~~~~~~~~~~~~~~~~~~~~~~~~~
                var winword = new Microsoft.Office.Interop.Word.Application();
                winword.ShowAnimation = false;
                winword.Visible       = false;
                object winWordMissing = System.Reflection.Missing.Value;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

                while (documentCount < filesToCreateTemp)
                {
                    wordFileNameDateFinal = wordFileNameDate + "_" + documentCount;
                    // ~~~~~~ create word files (vary formatting)
                    try
                    {
                        if (frm1.varyFormatting)
                        {
                            //Selecting random lorem text length
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);
                            int    rLorem4 = r.Next(0, 2);
                            int    rLorem5 = r.Next(0, 2);

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

                            //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      = frm1.lorems[rLorem4];
                            }

                            //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 = frm1.lorems[rLorem5];
                            }

                            //adding text to document
                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Add paragraph with Heading 1 style
                            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading1 = "Heading 1";
                            para1.Range.set_Style(ref styleHeading1);
                            para1.Range.Text = frm1.lorems[rLorem1];
                            para1.Range.InsertParagraphAfter();

                            //Add paragraph with Heading 2 style
                            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref winWordMissing);
                            object styleHeading2 = "Heading 2";
                            para2.Range.set_Style(ref styleHeading2);
                            para2.Range.Text = frm1.lorems[rLorem2];
                            para2.Range.InsertParagraphAfter();

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                        else // ~~~~~~ create word files (NO formatting)
                        {
                            //adding text to document
                            Random r       = new Random(DateTime.Now.Millisecond);
                            int    rLorem1 = r.Next(0, 5);
                            int    rLorem2 = r.Next(0, 5);
                            int    rLorem3 = r.Next(0, 5);

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

                            document.Content.SetRange(0, 0);
                            document.Content.Text = frm1.lorems[rLorem1] + "\r\n";
                            // adding some delay
                            if (frm1.addDelay)
                            {
                                Thread.Sleep(frm1.addDelaySec * 1000);
                            }
                            document.Content.Text = frm1.lorems[rLorem2] + "\r\n";
                            document.Content.Text = frm1.lorems[rLorem3];

                            //Save the document
                            object filename = workingDir + wordFileNameDateFinal + ".docx";
                            //object filename = filePath + "\\" + fileName + ".docx";
                            document.SaveAs2(ref filename);
                            // Keeping a list of files created
                            frm1.listOfWordFiles.Add(filename.ToString());
                            document.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            document = null;
                            if (document != null)
                            {
                                Marshal.ReleaseComObject(document);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error creating Word file!");
                        Console.WriteLine(ex.Message);
                    }
                    documentCount++;
                }

                // ~~~~~~ copy some of the documents
                int i2 = 0;
                while (i2 < filesToCreateTemp)
                {
                    if (i2 % 4 == 0)
                    {
                        string filePathNoExtension = frm1.listOfWordFiles[i2].Substring(0, frm1.listOfWordFiles[i2].Length - 5);
                        string newFilePathCopy     = filePathNoExtension + "_copy" + ".docx";
                        try
                        {
                            var originalDocument = winword.Documents.Open(frm1.listOfWordFiles[i2]); // Open original document

                            originalDocument.ActiveWindow.Selection.WholeStory();                    // Select all in original document
                            var originalText = originalDocument.ActiveWindow.Selection;              // Copy everything to the variable

                            var newDocument          = new Word.Document();                          // Create new Word document
                            newDocument.Range().Text = originalText.Text;                            // Pasete everything from the variable
                            newDocument.SaveAs(newFilePathCopy);                                     // maybe SaveAs2??                  // Save the new document

                            originalDocument.Close(false);
                            newDocument.Close();

                            if (originalDocument != null)
                            {
                                Marshal.ReleaseComObject(originalDocument);
                            }
                            if (newDocument != null)
                            {
                                Marshal.ReleaseComObject(newDocument);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error coping documents");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i2++;
                }

                // ~~~~~~ find-replace in some documents
                int i3 = 0;
                while (i3 < filesToCreateTemp)
                {
                    if (i3 % 3 == 0)
                    {
                        try
                        {
                            Microsoft.Office.Interop.Word.Document aDoc = winword.Documents.Open(frm1.listOfWordFiles[i3], ReadOnly: false, Visible: false);
                            aDoc.Activate();

                            winword.Selection.Find.Execute(frm1.textToSearch1, false, true, false, false, false, true, 1, false, frm1.textToReplace1, 2, false, false, false, false);
                            winword.Selection.Find.Execute(frm1.textToSearch2, false, true, false, false, false, true, 1, false, frm1.textToReplace2, 2, false, false, false, false);

                            aDoc.SaveAs2();

                            aDoc.Close(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                            aDoc = null;
                            if (aDoc != null)
                            {
                                Marshal.ReleaseComObject(aDoc);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error in find-replace");
                            Console.WriteLine(ex.Message);
                        }
                    }
                    i3++;
                }

                // ~~~~~~~~~~~~~~~~~~~~ Terminating Word instance ~~~~~~~~~~~~~~~~~~~
                winword.Quit(ref winWordMissing, ref winWordMissing, ref winWordMissing);
                winword.Quit();
                if (winword != null)
                {
                    Marshal.ReleaseComObject(winword);
                }
                winword        = null;
                winWordMissing = null;
                // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            }
            catch (Exception ex)
            {
                Console.WriteLine("backGroundWorker WordCreate Error");
                Console.WriteLine(ex.Message);
            }

            tskCreateWordsRunning = false;
            Console.WriteLine();
            Console.WriteLine("runEverything(): createWords() -> DONE");
        }
Ejemplo n.º 32
0
        private void AddEntry(RecordSearch record)
        {
            //Date
            Word.Paragraph dateHeader = document.Content.Paragraphs.Add(ref missing);
            dateHeader.Range.Paragraphs.SpaceAfter = 0;
            try
            {
                dateHeader.Range.Text = record.DateOfResponse.ToDateString() + "\n";
            }
            catch
            {
                dateHeader.Range.Text       = "Missing date of response.";
                dateHeader.Range.Font.Bold  = 1;
                dateHeader.Range.Font.Color = Word.WdColor.wdColorDarkRed;
                _errorCount++;
            }
            dateHeader.Range.InsertParagraphAfter();


            //Address, PEID, & Invoice #
            Word.Table iTable = document.Tables.Add(dateHeader.Range, 1, 3, ref missing, ref missing);
            iTable.AllowAutoFit = true;
            iTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow);
            iTable.Columns[1].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent;
            iTable.Columns[1].PreferredWidth     = 40;
            iTable.Columns[2].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent;
            iTable.Columns[2].PreferredWidth     = 30;

            //--Address
            if (record.BillingAddress.ValidateMinimalCompleteness())
            {
                if (string.IsNullOrWhiteSpace(record.BillingAddress.AddressLine2))
                {
                    iTable.Rows[1].Cells[1].Range.Text = string.Format("{0}\r\n{1}\r\n{2}, {3} {4}",
                                                                       record.BillingAddress.AddressName, record.BillingAddress.AddressLine1, record.BillingAddress.City, record.BillingAddress.State, record.BillingAddress.ZIP);
                }
                else
                {
                    iTable.Rows[1].Cells[1].Range.Text = string.Format("{0}\r\n{1}\r\n{2}\r\n{3}, {4} {5}",
                                                                       record.BillingAddress.AddressName, record.BillingAddress.AddressLine1, record.BillingAddress.AddressLine2, record.BillingAddress.City, record.BillingAddress.State, record.BillingAddress.ZIP);
                }
            }
            else
            {
                iTable.Rows[1].Cells[1].Range.Text       = "Missing billing address information.";
                iTable.Rows[1].Cells[1].Range.Font.Bold  = 1;
                iTable.Rows[1].Cells[1].Range.Font.Color = Word.WdColor.wdColorDarkRed;
                _errorCount++;
            }

            //--PEID
            if (!string.IsNullOrWhiteSpace(record.ClientModel.NewPEID))
            {
                iTable.Rows[1].Cells[2].Range.Text = string.Format("PEID # " + record.ClientModel.NewPEID);
            }
            else if (!string.IsNullOrWhiteSpace(record.ClientModel.OldPEID))
            {
                iTable.Rows[1].Cells[2].Range.Text = string.Format("PEID # " + record.ClientModel.OldPEID);
            }
            else
            {
                iTable.Rows[1].Cells[2].Range.Text       = "Missing PEID.";
                iTable.Rows[1].Cells[2].Range.Font.Bold  = 1;
                iTable.Rows[1].Cells[2].Range.Font.Color = Word.WdColor.wdColorDarkRed;
                _errorCount++;
            }
            iTable.Rows[1].Cells[2].Range.Bold = 1;
            iTable.Rows[1].Cells[2].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;


            //--Invoice #
            iTable.Rows[1].Cells[3].Range.Text = "Invoice #";
            iTable.Rows[1].Cells[3].Range.Bold = 1;
            iTable.Range.InsertParagraphAfter();


            //Person, Project Name, Requestor, IC File #
            Word.Paragraph projectInfo = document.Content.Paragraphs.Add(ref missing);

            string attentionTo;

            if (string.IsNullOrWhiteSpace(record.BillingAddress.AttentionTo))
            {
                attentionTo = "";
            }
            else
            {
                attentionTo = "\r\nATTN: " + record.BillingAddress.AttentionTo;
            }
            string fileNumber = "IC File # " + record.GetFileNumberFormatted();

            if (string.IsNullOrWhiteSpace(record.Requestor.FirstName))
            {
                projectInfo.Range.Text = string.Format("{0}\r\n>>\r\nRE: {1}; {2}\r\n>>",
                                                       attentionTo, record.ProjectName, fileNumber);
            }
            else
            {
                projectInfo.Range.Text = string.Format("{0}\r\n>>\r\nRE: {1} (Requested By: {2} {3}); {4}\r\n>>",
                                                       attentionTo, record.ProjectName, record.Requestor.FirstName, record.Requestor.LastName, fileNumber);
            }

            object startRange = projectInfo.Range.End - (fileNumber.Length + 4);
            object endRange   = projectInfo.Range.End - 3;

            Word.Range toBold = document.Range(ref startRange, ref endRange);
            toBold.Bold = 1;
            projectInfo.Range.InsertParagraphAfter();


            //Billing Info
            Word.Table bTable = document.Content.Tables.Add(projectInfo.Range, 1, 2, ref missing);
            bTable.AllowAutoFit = true;
            bTable.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitWindow);
            bTable.Columns[1].PreferredWidthType = Word.WdPreferredWidthType.wdPreferredWidthPercent;
            bTable.Columns[1].PreferredWidth     = 25;

            //--Total
            try
            {
                bTable.Rows[1].Cells[1].Range.Text = "Amount Due: $" + record.Fee.TotalProjectCost;
            }
            catch
            {
                bTable.Rows[1].Cells[1].Range.Text       = "Missing PEID.";
                bTable.Rows[1].Cells[1].Range.Font.Bold  = 1;
                bTable.Rows[1].Cells[1].Range.Font.Color = Word.WdColor.wdColorDarkRed;
                _errorCount++;
            }

            //--Fees & Surcharge
            string  chargeInformation = "";
            decimal runningTotal      = 0;

            foreach (ICharge charge in record.Fee.Charges)
            {
                if (charge.TotalCost <= 0)
                {
                    continue;
                }
                switch (charge.Type)
                {
                case "variable":
                    VariableCharge vCharge = (VariableCharge)charge;
                    chargeInformation += string.Format("  {0} - {1} {2} @ ${3} per {4}\n",
                                                       vCharge.Name, vCharge.Count, vCharge.UnitNamePlural, vCharge.Cost, vCharge.UnitName);
                    runningTotal += vCharge.TotalCost;
                    break;

                case "boolean":
                    BooleanCharge bCharge = (BooleanCharge)charge;
                    chargeInformation += string.Format("  {0} - ${1}\n", bCharge.Name, bCharge.TotalCost);
                    runningTotal      += bCharge.TotalCost;
                    break;

                case "categorical":
                    CategoricalCharge cCharge = (CategoricalCharge)charge;
                    chargeInformation += string.Format("  {0} - {1} {2} - ${3}\n", cCharge.Name, cCharge.Count, cCharge.UnitNamePlural, cCharge.TotalCost);
                    runningTotal      += cCharge.TotalCost;
                    break;

                default:
                    break;
                }
            }

            string surcharge = "";

            if (record.Fee.IsPriority)
            {
                surcharge += "  Priority Surcharge Fee: $" + (record.Fee.TotalProjectCost - runningTotal) + "\n";
            }
            if (record.Fee.IsEmergency)
            {
                surcharge += "  Emergency Surcharge Fee: $" + record.Fee.TotalProjectCost + "\n";
            }

            bTable.Rows[1].Cells[2].Range.Text = "Information\n" + chargeInformation + surcharge + "Please include the invoice number on your remittance";
            bTable.Range.InsertParagraphAfter();

            //Finish with line
            InsertLine();
        }
        private static void AddMarkingHeaderToDocument(ProtectiveMarking marking, Word.Document document)
        {
            Debug.WriteLine("PspfMarkingsAddIn: AddMarkingHeaderToDocument");
            Debug.WriteLine("==============================================================================");

            Word.Range           range  = null;
            Word.Font            font   = null;
            Word.ParagraphFormat format = null;

            try
            {
                object start = 0;
                object end   = 0;

                // Move to start
                range = document.Range(ref start, ref end);

                // Insert Paragraph break
                range.InsertParagraphAfter();

                Marshal.ReleaseComObject(range);

                // Move to start
                range = document.Range(ref start, ref end);

                range.Text = marking.MailBodyHeaderText;

                font = range.Font;

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderColour))
                {
                    var colorConverter = new ColorConverter();

                    var color = (Color)colorConverter.ConvertFromString(marking.MailBodyHeaderColour);

                    font.Color = (Word.WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B);
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderSizePoints))
                {
                    font.Size = float.Parse(marking.MailBodyHeaderSizePoints);
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderFont))
                {
                    font.Name = marking.MailBodyHeaderFont;
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderAlign))
                {
                    format = range.ParagraphFormat;

                    switch (marking.MailBodyHeaderAlign.ToLowerInvariant())
                    {
                    case "center":
                    case "centre":
                    case "middle":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        break;

                    case "left":
                    case "normal":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                        break;

                    case "right":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                        break;

                    default:
                        Debug.WriteLine("Unexpected text alignment: " + marking.MailBodyHeaderAlign);
                        break;
                    }
                }

                // Force the edit to persist:
                document.Activate();
            }
            finally
            {
                if (format != null)
                {
                    Marshal.ReleaseComObject(format);
                }

                if (font != null)
                {
                    Marshal.ReleaseComObject(font);
                }

                if (range != null)
                {
                    Marshal.ReleaseComObject(range);
                }
            }
        }
Ejemplo n.º 34
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Document wd = new Word.Document();
            wd.Activate();
            Object start = Type.Missing;
            Object end   = Type.Missing;

            wd.Content.Font.Size = 12;
            wd.Content.Font.Name = "Times New Roman";
            wd.Content.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            Word.Range rng = wd.Range(ref start, ref end);

            Word.Paragraph wordparagraph = wd.Paragraphs.Add();
            wordparagraph.Range.Text = "Государственное учреждение образования \"Институт бизнеса и менеджмента технологий\" Белорусского государственного университета";
            wordparagraph.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "Карточка №1";
            wordparagraph.Range.Font.Size = 14;
            wordparagraph.Range.Bold      = 1;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "(учета проведенных занятий)";
            wordparagraph.Range.Font.Size = 14;
            wordparagraph.Range.Bold      = 1;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text      = "Преподаватель";
            wordparagraph.Range.Font.Size = 12;
            wordparagraph.Range.Bold      = 0;
            wordparagraph.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Факультет";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Специальность";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Курс                                    \t\tГруппа             ";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Учебный год                                    \tСеместр             ";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Учебная дисциплина";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Количество часов по плану";
            wordparagraph.Range.InsertParagraphAfter();

            wordparagraph.Range.Text = "Форма занятий";
            wordparagraph.Range.InsertParagraphAfter();

            rng.SetRange(rng.End, rng.End);
            Object defaultTableBehavior = Type.Missing;
            Object autoFitBehavior      = Type.Missing;

            Word.Table tbl = wd.Tables.Add(rng, 1, 7, ref defaultTableBehavior, ref autoFitBehavior);
            SetHeadings(tbl.Cell(1, 1), "№ п/п");
            SetHeadings(tbl.Cell(1, 2), "Тема");
            SetHeadings(tbl.Cell(1, 3), "Тип");
            SetHeadings(tbl.Cell(1, 4), "Дата");
            SetHeadings(tbl.Cell(1, 5), "Время");
            SetHeadings(tbl.Cell(1, 6), "Кол. часов");
            SetHeadings(tbl.Cell(1, 7), "Подпись");
            int i;

            for (i = 0; i < lecturerData.Rows.Count; i++)
            {
                string   s   = lecturerData.Rows[i][3].ToString();
                string[] w   = s.Split('.');
                string   res = w[1];
                if (res == curNumMonth)
                {
                    Word.Row newRow = wd.Tables[1].Rows.Add();
                    newRow.Range.Font.Bold = 0;
                    newRow.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    newRow.Cells[1].Range.Text             = lecturerData.Rows[i][0].ToString();
                    tbl.Columns[1].SetWidth(27, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[2].Range.Text = lecturerData.Rows[i][1].ToString();
                    tbl.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustSameWidth);
                    string typeOfLesson = lecturerData.Rows[i][2].ToString();
                    if (typeOfLesson == "Управляемая самостоятельная работа")
                    {
                        newRow.Cells[3].Range.Text = "УСР";
                    }
                    else if (typeOfLesson == "Лабораторная работа")
                    {
                        newRow.Cells[3].Range.Text = "Лаб";
                    }
                    else
                    {
                        newRow.Cells[3].Range.Text = lecturerData.Rows[i][2].ToString();
                    }
                    tbl.Columns[3].SetWidth(60, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[4].Range.Text = lecturerData.Rows[i][3].ToString();
                    tbl.Columns[4].SetWidth(65, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[5].Range.Text = lecturerData.Rows[i][4].ToString();
                    tbl.Columns[5].SetWidth(44, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[6].Range.Text = lecturerData.Rows[i][5].ToString();
                    tbl.Columns[6].SetWidth(40, Word.WdRulerStyle.wdAdjustSameWidth);
                    newRow.Cells[7].Range.Text = lecturerData.Rows[i][6].ToString();
                    tbl.Columns[7].SetWidth(60, Word.WdRulerStyle.wdAdjustSameWidth);
                }
            }
            //i++;
            //wd.Tables[1].Rows.Add();
            //tbl.Rows[i].Cells[0].Merge(tbl.Rows[i].Cells[2]);
        }
		public int Export_exam(int id)
		{
            
            Exam exam = (from e in context.Exams
                         where e.Id == id
                         select e).SingleOrDefault();
            string examName = "";

            examName = "Subject : "+exam.NameExam.ToString()+"\r";
            string nameFile = exam.NameExam.ToString();

            try
            {
                examName += "Question number: " + exam.QuestionNumber.ToString() + "\r";
                //titleExam += (from t in context.Tests
                //              where t.ExamId == id
                //              select new
                //              {
                //                  TestTime = t.TestTime
                //              }
                //              ).ToString() +"\r";

                Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                object missing = System.Reflection.Missing.Value;
               
                Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                Microsoft.Office.Interop.Word.Range range = document.Range();
                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 = 24;
                    
                    headerRange.Text = examName;

                }
                string tempSave = string.Empty;

                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 = "Footer text goes here";

                    var exams = (from eq in context.ExamQuestions
                                 where eq.ExamId == id
                                 select new
                                 {
                                     QuestionId = eq.QuestionId
                                 }).ToList();
                    int countExam =  1;

                    foreach (var item in exams)
                    {
                        long temp = Convert.ToInt64(item.QuestionId);
                        List<Question> ques = (from q in context.Questions
                                               where q.Id == temp

                                               select q).ToList();
                        foreach (Question itemq in ques)
                        {

                            ///document.Content.CopyAsPicture();
                            string quesText = itemq.Content.ToString();
                            
                            //document.Content.Text = quesText + Environment.NewLine + Environment.NewLine;

                            tempSave += "Question "+countExam+" : "+itemq.Content + '\r';
                            List<Answer> answers = (from a in context.Answers
                                                    where a.Question.Id == temp
                                                    select a
                                                    ).ToList();
                            int characterAbc = 0;
                            char character = 'A';
                            characterAbc = (int)character;
                            foreach (var itemAns in answers)
                            {
                                
                                string answer = (char)(characterAbc) + ". "+ itemAns.Content.ToString();
                                
                                tempSave += answer + "\r";
                                characterAbc++;
                            }
                            countExam++;
                            tempSave += "\r";
                        }
                        
                    }
                    //object rangeABC = range.InlineShapes.AddPicture(@"C:\Users\LeCuong\OneDrive\Desktop\Untitled.jpg");


                    //Range rngPic = document.Tables[1].Range;

                    //rngPic.InlineShapes.AddPicture(@"C:\Users\LeCuong\Desktop\Untitled.jpg");

                    //float leftPosition = (float)this.Application.Selection.Information[WdInformation.wdHorizontalPositionRelativeToPage];


                    //var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)));
                    //string configLocation = requiredPath.ToString().Substring(6)+ "\\WebApi\\Content\\ConfigLocation\\ConfigLocation.txt";


                    //string configText = File.ReadAllText(configLocation);

                    //document.Content.Text = tempSave;
                    //object filename = configText+nameFile+"cuong"+id+".docx";
                    object filename = @"D:\"+nameFile + id + ".docx";
                    document.SaveAs2(ref filename);
                    
                }
                string abc = document.Content.Text;
                document.Close(ref missing, ref missing, ref missing);
                document = null;
                winword.Quit(ref missing, ref missing, ref missing);
                winword = null;

            }
            catch (Exception ex)
            {
                throw;
            }
            return 1;
			
		}
Ejemplo n.º 36
0
 public static void message(String msg)
 {
     Word.Document doc = ThisAddIn.getCurrDocument();
     Word.Range    rng = doc.Range(0, 0);
     rng.Text = msg;
 }
Ejemplo n.º 37
0
        public void Otchet_To_Word(DataGridView dataGridViewMain, string filename)// Метод экспорта в Word
        {
            Word.Document oDoc = new Word.Document();
            oDoc.Application.Visible = true;
            //ориентация страницы
            oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait;
            // Стиль текста.
            object start = 0, end = 0;

            Word.Range rng = oDoc.Range(ref start, ref end);
            rng.InsertBefore("Отчет");//Заголовок
            rng.Font.Name = "Times New Roman";
            rng.Font.Size = 12;
            rng.InsertParagraphAfter();
            rng.InsertParagraphAfter();
            rng.SetRange(rng.End, rng.End);
            oDoc.Content.ParagraphFormat.LeftIndent = oDoc.Content.Application.CentimetersToPoints(0); // отступ слева
            oDoc.Paragraphs.Format.FirstLineIndent  = 0;                                               //Отступ первой строки
            oDoc.Paragraphs.Format.LineSpacing      = 8;                                               //межстрочный интервал в первом абзаце.(высота строк)
            oDoc.Paragraphs.Format.SpaceBefore      = 3;                                               //межстрочный интервал перед первым абзацем.
            oDoc.Paragraphs.Format.SpaceAfter       = 1;                                               //межстрочный интервал после первого абзаца.

            if (dataGridViewMain.Rows.Count != 0)
            {
                //удаление столбца
                //this.dataGridView1.Columns.RemoveAt(4);//дата записи

                string   kol_vo      = Convert.ToString(textBoxAmount.Text); //кол-во
                string   sum         = Convert.ToString(textBoxSumm.Text);   //сумма
                DateTime month       = Convert.ToDateTime(dataGridViewMain.Rows[0].Cells[4].Value);
                int      RowCount    = dataGridViewMain.Rows.Count;
                int      ColumnCount = dataGridViewMain.Columns.Count - 1;// столбцы в гриде (-5 последних)
                Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];
                // добавить строки
                int r = 0;
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    for (r = 0; r <= RowCount - 1; r++)
                    {
                        DataArray[r + 1, c] = dataGridViewMain.Rows[r].Cells[c].Value;// +1 это первая строка в таблице над заголовком
                    } //Конец цикла строки
                } //конец петли колонки
                  //Добавление текста в документ

                oDoc.Content.SetRange(0, 0);// для текстовых строк
                oDoc.Content.Text = "                                                                                   Кол-во: " + kol_vo + "     Сумма: " + sum +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine +
                                    Environment.NewLine + "Начальник транспортного отдела " +
                                    Environment.NewLine +
                                    Environment.NewLine + "______________________________" +
                                    Environment.NewLine;

                dynamic oRange = oDoc.Content.Application.Selection.Range;
                string  oTemp  = "";
                for (r = 0; r <= RowCount - 1; r++)
                {
                    for (int c = 0; c <= ColumnCount - 1; c++)
                    {
                        oTemp = oTemp + DataArray[r, c] + "\t";
                    }
                }
                //формат таблицы
                oRange.Text = oTemp;
                object Separator       = Word.WdTableFieldSeparator.wdSeparateByTabs;
                object ApplyBorders    = true;
                object AutoFit         = true;
                object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;

                oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,
                                      Type.Missing, Type.Missing, ref ApplyBorders,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);

                oRange.Select();
                oDoc.Application.Selection.Tables[1].Select();
                oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;
                oDoc.Application.Selection.Tables[1].Rows.Alignment             = 0;
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.InsertRowsAbove(1);
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                //стиль строки заголовка
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold      = 1;
                oDoc.Application.Selection.Tables[1].Rows[2].Range.Bold      = 1;
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = "Times New Roman";
                oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 9;
                //добавить строку заголовка вручную
                for (int c = 0; c <= ColumnCount - 1; c++)
                {
                    oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = "";
                    oDoc.Application.Selection.Tables[1].Cell(2, c + 1).Range.Text = dataGridViewMain.Columns[c].HeaderText;
                }
                //стиль таблицы
                oDoc.Application.Selection.Tables[1].Columns[3].Delete();                                                                //Удалить столбец
                oDoc.Application.Selection.Tables[1].Columns[3].Delete();                                                                //Удалить столбец
                oDoc.Application.Selection.Tables[1].Columns[4].Delete();                                                                //Удалить столбец

                oDoc.Application.Selection.Tables[1].Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //Выравнивание текста в таблице по центру
                oDoc.Application.Selection.Tables[1].Rows.Borders.Enable             = 1;                                                //borders
                oDoc.Application.Selection.Tables[1].Rows[1].Select();
                oDoc.Application.Selection.Cells.VerticalAlignment    = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                oDoc.Application.Selection.Tables[1].Columns[1].Width = 120; //ширина столбца
                oDoc.Application.Selection.Tables[1].Columns[2].Width = 120; //ширина столбца
                oDoc.Application.Selection.Tables[1].Columns[3].Width = 80;  //ширина столбца
                oDoc.Application.Selection.Tables[1].Columns[4].Width = 80;  //ширина столбца
                oDoc.Application.Selection.Tables[1].Columns[5].Width = 120; //ширина столбца
                //oDoc.Application.Selection.Tables[1].Columns[6].Width = 60;//ширина столбца
                //oDoc.Application.Selection.Tables[1].Columns[7].Width = 80;//ширина столбца
                oDoc.Application.Selection.Tables[1].LeftPadding     = 1;   //отступ с лева полей ячеек
                oDoc.Application.Selection.Tables[1].RightPadding    = 1;   //отступ с права полей ячеек
                oDoc.Application.Selection.Tables[1].Rows.LeftIndent = -30; //Установка отступа слева
                //oDoc.Application.Selection.Tables[1].Cell(1, 2).Range.Text = "текст в ячейке";
                //oDoc.Application.Selection.Tables[1].Cell(1, 2).Merge(oDoc.Application.Selection.Tables[1].Cell(1, 4));//Объединение
                //текст заголовка
                foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)
                {
                    // Верхний колонтитул
                    DateTime   Now         = DateTime.Now;
                    Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range;
                    headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);
                    section.PageSetup.DifferentFirstPageHeaderFooter = -1;//Включить особый колонтитул
                    headerRange.Text =
                        Environment.NewLine +
                        Environment.NewLine +
                        Environment.NewLine +
                        Environment.NewLine +
                        Environment.NewLine + "Сводный отчет" +
                        Environment.NewLine + "по ремонту и обслуживанию автомобилей" +
                        Environment.NewLine + "ГП Службы специальной связи" +
                        Environment.NewLine + "с " + Convert.ToString(dateTimePickerStart.Value.ToString("dd.MM.yyyy")) + " по " + Convert.ToString(dateTimePickerEnd.Value.ToString("dd.MM.yyyy")) +
                        Environment.NewLine;

                    headerRange.Font.Size = 14;
                    headerRange.Font.Name = "Times New Roman";
                    headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    // Нижний колонтитул
                    Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage);
                    footerRange.Text      = "Служба специальной связи       " + Convert.ToString(Now.ToString("dd.MM.yyyy"));
                    footerRange.Font.Size = 9;
                    footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                }
                //сохранить файл
                oDoc.SaveAs(filename);
            }
        }
Ejemplo n.º 38
0
        public override void SaveFileAs(string fileName, FileType type)
        {
            object Visible = false;
            object start1 = 0;
            object end1 = 0;

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

            doc.SaveAs(ref filename, ref missing, ref missing,
                                ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing, ref missing);

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