Ejemplo n.º 1
0
        /// <summary>
        /// Объединение нескольких документов word в один
        /// </summary>
        /// <param name="filePathOutput">Имя выходного файла</param>
        /// <param name="mergeDocs">Массив имен файлов, из которых будет скопировано содержимое в выходной файл</param>
        public static void MergerDocs(string filePathOutput, string[] mergeDocs)
        {
            object sectionBreak = Word.WdBreakType.wdSectionBreakNextPage;

            Word.Application app = null;
            try
            {
                app = new Word.Application();
                Word.Document  doc       = app.Documents.Add();
                Word.Selection selection = app.Selection;
                for (int i = 0; i < mergeDocs.Length; i++)
                {
                    selection.InsertFile(mergeDocs[i]);
                    if (i != mergeDocs.Length - 1)
                    {
                        selection.InsertBreak(sectionBreak);
                    }
                }
                doc.SaveAs2(filePathOutput);
                doc.Close();
            }
            finally
            {
                try
                {
                    app.Quit();
                }
                catch (Exception) { }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 多选题
        /// </summary>
        private void creatMultipleSelection()
        {
            Word.Selection focusSelect = Globals.ThisAddIn.Application.Selection;
            focusSelect.TypeParagraph();
            focusSelect.TypeParagraph();
            focusSelect.Font.Bold = 1;
            focusSelect.TypeText("二、多选题");
            focusSelect.Font.Bold = 0;
            focusSelect.TypeText("(共6题;共24分)\n");

            int[] multipleSelectionList = new int[6];
            multipleSelectionList = myRandom(6, MyGlobal.MultipleSelection.Rows.Count); // 获取要打印的题目集合
            for (int i = 0; i < 6; i++)
            {
                focusSelect.TypeParagraph();
                // 打印题目
                focusSelect.TypeText((i + 7).ToString() + ".(4分)" +
                                     MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["Squestion"].ToString() + "\n");

                // 打印图片
                if (MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["Spicture"].ToString() != string.Empty)
                {
                    focusSelect.InlineShapes.AddPicture(SqlAndPath.PicturePath + "\\" +
                                                        MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["Spicture"].ToString());
                    focusSelect.TypeParagraph();
                }

                // 打印选择题
                focusSelect.TypeText("A." + MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["SoptionA"].ToString() + "\n");
                focusSelect.TypeText("B." + MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["SoptionB"].ToString() + "\n");
                focusSelect.TypeText("C." + MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["SoptionC"].ToString() + "\n");
                focusSelect.TypeText("D." + MyGlobal.MultipleSelection.Rows[multipleSelectionList[i] - 1]["SoptionD"].ToString() + "\n");
            }
        }
        /// <summary>
        /// Create a new CC if not already in one.
        /// </summary>
        /// <param name="controlType"></param>
        /// <param name="docx"></param>
        /// <param name="selection"></param>
        /// <returns></returns>
        public static Word.ContentControl MakeOrReuse(bool tryToReuse, Word.WdContentControlType controlType,
                                                      Word.Document docx, Word.Selection selection)
        {
            // step 1: create content control, if necessary
            // are we in a content control?
            Word.ContentControl cc = null;
            if (tryToReuse)
            {
                cc = ContentControlMaker.getActiveContentControl(docx, selection);
            }
            object missing = System.Type.Missing;

            if (cc == null)
            {
                // Add one
                cc       = docx.ContentControls.Add(controlType, ref missing);
                cc.Title = "[New]";
            }
            else
            {
                // we're in a content control already.
                // Have they selected all of it?
                // If so, is this add or re-map?
                if (controlType.Equals(Word.WdContentControlType.wdContentControlRichText))
                {
                    cc.XMLMapping.Delete();
                }
                cc.Type = controlType;
            }

            return(cc);
        }
Ejemplo n.º 4
0
        private void Spajanje()
        {
            object template     = pp.Substring(0, pp.LastIndexOf(@"\") + 1) + @"Normal.dot";
            string fullName     = _putanja + @"\" + "Spojeno" + ext;
            object fname        = fullName;
            object missing      = System.Type.Missing;
            object sectionBreak = WORD.WdBreakType.wdSectionBreakNextPage;

            try
            {
                WORD._Document doca = app.Documents.Add(ref template, ref missing, ref missing, ref missing);
                doca.PageSetup.TopMargin = 1.46F;
                WORD.Selection selection  = app.Selection;
                String         insertFile = "";
                foreach (string s in ucenici)
                {
                    insertFile = _putanja + @"\" + s;
                    selection.InsertFile(insertFile, ref missing, ref missing, ref missing, ref missing);
                }
                doca.SaveAs(ref fname);
            }
            finally
            {
                app.Quit();
            }
        }
Ejemplo n.º 5
0
        private void Chengban_Tongzhi(Word.Application wordApp)
        {
            GotoLastLine(wordApp);
            Word.Selection ws = wordApp.Selection;
            GotoLastCharacter(ws);
            ws.TypeParagraph();
            ws.TypeParagraph();
            ws.Font.Size = 14;
            ws.Font.Name = "仿宋";
            ws.ParagraphFormat.CharacterUnitFirstLineIndent = 0;
            ws.TypeText("抄送:" + textBox1.Text + ChaoSong_Space("抄送:" + textBox1.Text + "(共印" + textBox3.Text + "份)") + "(共印" + textBox3.Text + "份)");
            ws.TypeParagraph();
            //计算承办信息第二行空格数
            string cSqace = ChengBan_Space("承办单位:" + comboBox5.Text + "承办人:" + textBox4.Text + "电话:" + textBox5.Text);

            ws.TypeText("承办单位:" + comboBox5.Text + cSqace + "承办人:" + textBox4.Text + cSqace + "电话:" + textBox5.Text);
            ws.TypeParagraph();
            ws.TypeText(label12.Text + YinFa_Space(label12.Text + dateTimePicker2.Text + label13.Text) + dateTimePicker2.Text + label13.Text);

            //给承办信息部分划线
            Word.Document ad = wordApp.ActiveDocument;
            int           p  = ad.Paragraphs.Count;

            ad.Paragraphs[p - 2].Borders[Word.WdBorderType.wdBorderTop].LineStyle    = Word.WdLineStyle.wdLineStyleSingle;
            ad.Paragraphs[p - 2].Borders[Word.WdBorderType.wdBorderTop].LineWidth    = Word.WdLineWidth.wdLineWidth100pt;
            ad.Paragraphs[p - 1].Borders[Word.WdBorderType.wdBorderTop].LineStyle    = Word.WdLineStyle.wdLineStyleSingle;
            ad.Paragraphs[p - 1].Borders[Word.WdBorderType.wdBorderTop].LineWidth    = Word.WdLineWidth.wdLineWidth075pt;
            ad.Paragraphs[p - 1].Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
            ad.Paragraphs[p - 1].Borders[Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth075pt;
            ad.Paragraphs[p].Borders[Word.WdBorderType.wdBorderBottom].LineStyle     = Word.WdLineStyle.wdLineStyleSingle;
            ad.Paragraphs[p].Borders[Word.WdBorderType.wdBorderBottom].LineWidth     = Word.WdLineWidth.wdLineWidth100pt;
        }
Ejemplo n.º 6
0
 private void ChengPiJianTou(Word.Application wordApp)
 {
     wordApp = Globals.ThisAddIn.Application;
     Word.Selection ws = wordApp.Selection;
     ws.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     ws.Font.Size = 16;
     ws.Font.Name = "黑体";
     ws.TypeText("01\r\n");
     ws.TypeText(comboBox1.Text + "\r\n");
     ws.TypeText(comboBox2.Text + "\r\n");
     ws.TypeParagraph();
     ws.TypeParagraph();
     ws.TypeParagraph();
     ws.TypeParagraph();
     ws.Font.Name = "宋体";
     ws.Font.Size = 22;
     ws.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
     ws.Font.ColorIndex           = Word.WdColorIndex.wdRed;
     ws.TypeText(comboBox_fwdw.Text + "呈批件");
     ws.Font.Size       = 16;
     ws.Font.ColorIndex = Word.WdColorIndex.wdBlack;
     ws.Font.Name       = "仿宋";
     ws.TypeParagraph();
     ws.TypeParagraph();
     ws.Paragraphs[1].Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
     ws.Paragraphs[1].Borders.OutsideLineWidth = Word.WdLineWidth.wdLineWidth150pt;
     ws.Paragraphs[1].Borders.OutsideColor     = Word.WdColor.wdColorRed;
     ws.Paragraphs[1].Borders[Word.WdBorderType.wdBorderLeft].LineStyle  = Word.WdLineStyle.wdLineStyleNone;
     ws.Paragraphs[1].Borders[Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleNone;
     ws.Paragraphs[1].Borders[Word.WdBorderType.wdBorderTop].LineStyle   = Word.WdLineStyle.wdLineStyleNone;
     ws.Font.Name = "仿宋";
     ws.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
     ws.TypeText("〔" + dateTimePicker1.Text + "〕" + textBox2.Text + "号                            " + textbox_qf.Text + "  签发");
 }
Ejemplo n.º 7
0
        public static void InsertDataToEndDocument(Word.Document document, DocumentEntity documentEntity)
        {
            TextHelpers.GoToEndDocument(document);
            Word.Selection selection = Globals.ThisAddIn.Application.Selection;
            foreach (DocumentParagraph documentParagraph in documentEntity.paragraphs)
            {
                if (documentParagraph.belongTo != null)
                {
                    selection.set_Style(document.Styles[Constants.RerpesentativeStyle]);

                    if (documentParagraph.belongTo.fullTitle != null)
                    {
                        selection.TypeText(documentParagraph.belongTo.fullTitle);
                    }
                    else if (documentParagraph.belongTo.name != null &&
                             documentParagraph.belongTo.duty != null)
                    {
                        selection.TypeText(Utils.FormatRepresentative(documentParagraph.belongTo.name, documentParagraph.belongTo.duty));
                    }
                    selection.TypeParagraph();
                }

                foreach (string content in documentParagraph.contents)
                {
                    if (!content.Trim().Equals(""))
                    {
                        selection.set_Style(document.Styles[Constants.ContentStyle]);
                        selection.TypeText(content.Trim());
                        selection.TypeParagraph();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        private void btn_ApplyBoilerplate_Click(object sender, RibbonControlEventArgs e)
        {
            //get the text from the settings
            StringCollection            bps  = Properties.Settings.Default.Options_StandardComments;
            Dictionary <string, string> dict = new Dictionary <string, string>();

            for (int i = 0; i < bps.Count - 1; i++)
            {
                dict.Add(bps[i], bps[i + 1]);
            }

            //Find out which option is selected
            RibbonDropDownItem item = this.dd_Boilerplate.SelectedItem;

            if (dict.ContainsKey(item.Label))
            {
                Word.Document  doc       = Globals.ThisAddIn.Application.ActiveDocument;
                Word.Selection selection = Globals.ThisAddIn.Application.Selection;
                if (selection != null && selection.Range != null)
                {
                    selection.Comments.Add(selection.Range, dict[item.Label]);
                }
                else
                {
                    MessageBox.Show("Could not find any selected text or valid insertion point. Please let Aaron know!");
                }
            }
            else
            {
                MessageBox.Show("An error occurred when finding your boilerplate. Please let Aaron know!");
                return;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 清除选中部分中每个段落结尾的空格/Tab
        /// </summary>
        internal static void TrimTrailing(Word.Selection selection)
        {
            var paragraphs = selection.Paragraphs;

            foreach (Word.Paragraph paragraph in paragraphs)
            {
                var characters     = paragraph.Range.Characters;
                var trimStartIndex = -1; // 指向第一个可删除字符
                // 反向查找连续的可删除字符,直接跳过末尾的换行符开始
                for (var i = characters.Count - 1; i > 0; i--)
                {
                    var character = characters[i];
                    switch (character.Text)
                    {
                    // 先检查空格,因使用`Alt+鼠标`框选模式时,选择面会超过段落末尾。超过末尾的虚拟空格内容也是“ ”。
                    case " ":
                    case "\t":
                        trimStartIndex = i;
                        continue;
                    }
                    // 不处理其他符号
                    break;
                }
                // 若找到了可删除字符索引,则可从它开始删除
                if (trimStartIndex > 0)
                {
                    characters[trimStartIndex].Delete(Word.WdUnits.wdCharacter, characters.Count - trimStartIndex);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Finds and replaces a string of text with an image specified at the given image file path
        /// </summary>
        private void ReplaceTextWithImage(string rawCommand, string imagePath, Word.Application wordApp)
        {
            Word.Selection sel     = wordApp.Selection;
            string         keyword = rawCommand;

            try {
                //Attempt to find the text that will be replaced.
                sel.Find.Execute(keyword, Replace: Word.WdReplace.wdReplaceOne);
            }
            catch (Exception) {
                string errorMessage = "Error parsing document command at command:\n" + keyword;
                if (keyword.Length > 250)
                {
                    errorMessage += "\n\nCommand exceeds maximum length";
                }
                MessageBox.Show(new Form {
                    TopMost = true
                }, errorMessage);
                wordApp.Quit();
                Environment.Exit(1);
            }
            //Select the text that was found.
            sel.Range.Select();
            //Get the full file path of the given image.
            var imagePath1 = Path.GetFullPath(string.Format(imagePath, keyword));

            //Replace the text with the image at the given path.
            sel.InlineShapes.AddPicture(imagePath, false, true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 设置文档格式并添加内容
        /// </summary>
        /// <param name="filePath">文件名</param>
        /// <returns></returns>
        public static bool AddContent(string filePath)
        {
            try
            {
                Object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application WordApp = new Application();
                WordApp.Visible = true;
                object filename = filePath;
                Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
                                                                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                                                         ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

                //设置居左
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

                //设置文档的行间距
                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
                //插入段落
                //WordApp.Selection.TypeParagraph();
                Microsoft.Office.Interop.Word.Paragraph para;
                para = WordDoc.Content.Paragraphs.Add(ref oMissing);
                //正常格式
                para.Range.Text = "This is paragraph 1";
                //para.Range.Font.Bold = 2;
                //para.Range.Font.Color = WdColor.wdColorRed;
                //para.Range.Font.Italic = 2;
                para.Range.InsertParagraphAfter();

                para.Range.Text = "This is paragraph 2";
                para.Range.InsertParagraphAfter();

                //插入Hyperlink
                Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection;
                mySelection.Start = 9999;
                mySelection.End   = 9999;
                Microsoft.Office.Interop.Word.Range myRange = mySelection.Range;

                Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;
                object linkAddr = @"http://www.cnblogs.com/lantionzy";
                Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr,
                                                                             ref oMissing);
                WordApp.ActiveWindow.Selection.InsertAfter("\n");

                //落款
                WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();
                WordDoc.Paragraphs.Last.Alignment  = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                //保存
                WordDoc.Save();
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
Ejemplo n.º 12
0
        public static void findNext(string txt, bool caseSens)
        {
            Word.Selection selecao    = Globals.ThisAddIn.Application.Selection;
            Word.Document  doc        = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Selection selection  = Globals.ThisAddIn.Application.ActiveDocument.Application.Selection;
            Word.Find      findObject = Globals.ThisAddIn.Application.Selection.Find;


            object findText = txt;

            selection.Find.ClearFormatting();
            selection.Find.Forward   = true;
            selection.Find.MatchCase = caseSens;
            selection.Find.Execute(ref findText);

            if (!selection.Find.Found)
            {
                doc.Range(0, 0).Select();
                selection.Find.Execute(ref findText);
                if (!selection.Find.Found)
                {
                    MessageBox.Show("Nenhuma ocorrência encontrada!");
                }
            }
        }
Ejemplo n.º 13
0
        public void SetCellsColor(int iCol1, int iCol2, int iRow1, int iRow2, MSWord.WdColor color, MSWord.WdColor text_color = MSWord.WdColor.wdColorAutomatic, int indTable = -1)
        {
            GetTableReference(indTable);

            MSWord.Cell pCell1 = m_pTable.Cell(iRow1, iCol1);
            if (pCell1 == null)
            {
                return;
            }
            MSWord.Cell pCell2 = m_pTable.Cell(iRow2, iCol2);
            if (pCell2 == null)
            {
                return;
            }

            MSWord.Range r = m_pDoc.Range(pCell1.Range.Start, pCell2.Range.End);
            r.Select();
            MSWord.Selection sel = m_pApp.Selection;
            sel.Shading.Texture = MSWord.WdTextureIndex.wdTextureNone;
            sel.Shading.ForegroundPatternColor = MSWord.WdColor.wdColorAutomatic;
            sel.Shading.BackgroundPatternColor = color;
            if (text_color != MSWord.WdColor.wdColorAutomatic)
            {
                sel.Font.Color = text_color;
            }
        }
Ejemplo n.º 14
0
 //TODO: [MethodImpl(MethodImplOptions.AggressiveInlining)]
 public static string GetCompleteWordAt(MSWord.Selection sel)
 {
     MSWord.Range word = sel.Document.Range(sel.Start, sel.End);
     word.StartOf(MSWord.WdUnits.wdWord, MSWord.WdMovementType.wdExtend);
     word.EndOf(MSWord.WdUnits.wdWord, MSWord.WdMovementType.wdExtend);
     return(word.Text);
 }
        public static Word.Selection MoveToLabel(Word.Selection s, string label)
        {
            object oUnit  = Word.WdUnits.wdStory;
            object oXtend = false;

            s.HomeKey(ref oUnit, ref oXtend);
            s.Find.ClearFormatting();
            object findText        = "$[" + label + "]";
            object matchCase       = false;
            object matchWholeWord  = false;
            object matchWildCards  = false;
            object matchSoundsLike = false;
            object matchAllForms   = false;
            object forward         = true;
            object wrap            = Word.WdFindWrap.wdFindContinue;
            object format          = false;
            object replaceWith     = "";
            object replace         = Word.WdReplace.wdReplaceNone;
            object matchKashida    = Type.Missing;
            object matchDiactrics  = Type.Missing;
            object matchAliH       = Type.Missing;
            object matchCOntrol    = Type.Missing;

            s.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards,
                           ref matchSoundsLike, ref matchAllForms, ref forward, ref wrap, ref format,
                           ref replaceWith, ref replace, ref matchKashida, ref matchDiactrics,
                           ref matchAliH, ref matchCOntrol);
            return(s);
        }
Ejemplo n.º 16
0
 private void DeleteFirstPage()
 {
     MSWord.Selection objSelection = winword.Selection;
     objSelection.GoTo(MSWord.WdGoToItem.wdGoToPage, MSWord.WdGoToDirection.wdGoToAbsolute, 1, 1);
     objSelection.Bookmarks[@"\Page"].Select();
     objSelection.Delete();
 }
Ejemplo n.º 17
0
        public string FindActiveWord(MSWord.Document doc)
        {
            string searchFor = "";

            MSWord.Selection sel = doc.Application.Selection;
            if (sel != null)
            {
                switch (sel.Type)
                {
                case MSWord.WdSelectionType.wdSelectionNormal:
                    if (sel.Text.Length == 1)
                    {
                        searchFor = GetCompleteWordAt(sel);
                    }
                    else
                    {
                        searchFor = sel.Text;
                    }
                    break;

                case MSWord.WdSelectionType.wdSelectionIP:
                    searchFor = GetCompleteWordAt(sel);
                    break;

                default:
                    throw new InvalidOperationException("Unknown selection type: " + sel.Type.ToString());
                }
            }

            return(searchFor.Trim());
        }
Ejemplo n.º 18
0
        private void InsertText(string text, string tag)
        {
            if (winword == null)
            {
                return;
            }

            MSWord.Selection       objSelection = winword.Selection;
            MSWord.Range           objRange     = objSelection.Range;
            MSWord.MailMergeFields wrdMergeFields;
            MSWord.ContentControls controls;

            if (tag != "")
            {
                controls = actualDocument.ContentControls;
                var contentctl = controls.Add(MSWord.WdContentControlType.wdContentControlRichText, objRange);
                contentctl.Tag = tag;
                var wrdMailMerge = actualDocument.MailMerge;
                wrdMergeFields = wrdMailMerge.Fields;
                wrdMergeFields.Add(contentctl.Range, text);
            }
            else
            {
                var wrdMailMerge = actualDocument.MailMerge;
                wrdMergeFields = wrdMailMerge.Fields;
                wrdMergeFields.Add(objRange, text);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Window select change event handler.
        /// </summary>
        /// <param name="selection">The selection.</param>
        void Application_WindowSelectionChange(Word.Selection selection)
        {
            // Initialize a summation
            double summation = 0;

            // Return early if the selection is not a collection of columns
            if (!Word.WdSelectionType.wdSelectionColumn.Equals(selection.Type) &&
                !Word.WdSelectionType.wdSelectionRow.Equals(selection.Type))
            {
                return;
            }

            // Iterate through the cells to get summation
            foreach (Word.Cell cell in selection.Cells)
            {
                double temp = 0;

                // Trim the tailing format chars
                if (double.TryParse(cell.Range.Text.TrimEnd(new char[] { '\r', '\a' }), out temp))
                {
                    summation += temp;
                }
            }

            // Change the status bar
            this.Application.StatusBar = $"The summation of selected numbers is {summation.ToString("N", CultureInfo.InvariantCulture)}";
        }
Ejemplo n.º 20
0
        // 在 word 文档中当前光标位置中插入指定路径下的图片
        #region InsertPicture
        /// <summary>
        /// 在 word 文档中当前光标位置中插入指定路径下的图片
        /// </summary>
        /// <param name="selection"></param>
        /// <param name="fullPath"></param>
        /// <param name="logInfo"></param>
        /// <returns></returns>
        public static bool InsertPicture(ref Word.Selection selection, string fullPath, out string logInfo)
        {
            bool res = true;

            try
            {
                object linkToFile       = false; //默认
                object saveWithDocument = true;  //默认
                //object drawrange = selection.Range;
                object           Nothing     = System.Reflection.Missing.Value;
                Word.InlineShape inlineShape = selection.InlineShapes.AddPicture(fullPath, ref linkToFile, ref saveWithDocument, ref Nothing);

                //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(drawPath);
                //double dpi = bmp.VerticalResolution; //96
                //设置图片大小
                int maxHeight = JCBase.Utility.Util.CentimeterToPixel(22, 72);//TODO:待确认 word 2003默认为72
                if (inlineShape.Height > maxHeight)
                {
                    inlineShape.Height = maxHeight;
                }


                logInfo = "图片插入成功!";
            }
            catch (Exception ex)
            {
                JCMsg.ShowErrorOK(ex.GetType().ToString() + "\n" + ex.Message);
                res     = false;
                logInfo = "图片插入失败!";
            }
            return(res);
        }
Ejemplo n.º 21
0
        private void resizepinyin_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
            if (currentSelection.Start == currentSelection.End)
            {
                currentSelection.MoveRight(Word.WdUnits.wdCharacter, 1, Word.WdMovementType.wdExtend);
            }

            Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;

            string     rangexml = currentRange.WordOpenXML;
            XDocument  doc      = XDocument.Parse(rangexml);
            XNamespace w        = doc.Descendants().First(x => x.Name.LocalName == "document").Name.Namespace;

            List <XElement> elements = doc.Descendants(w + "ruby").ToList();

            foreach (XElement ele in elements)
            {
                ele.Descendants(w + "hpsRaise").Remove(); // Remove lowering (e.g. if tone)
                string size = ele.Descendants(w + "hpsBaseText").Single().Attribute(w + "val").Value;
                if (0 < ele.Descendants(w + "rubyBase").Single().Descendants(w + "sz").Count())
                {
                    size = ele.Descendants(w + "rubyBase").Single().Descendants(w + "sz").First().Attribute(w + "val").Value;
                }
                ele.Descendants(w + "hpsBaseText").Single().SetAttributeValue(w + "val", size);
                Double sz = Double.Parse(pysize.Text) * Double.Parse(size);
                ele.Descendants(w + "hps").Single().Attribute(w + "val").SetValue(Math.Round(sz, 1).ToString());
            }

            currentRange.InsertXML(doc.ToString());
            currentRange.Select();
        }
        public bool Substituir(bool caseSensitive, string palavraBusca, string palavraSubstituir)
        {
            Word.Document  documentoAtual = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Selection range          = documentoAtual.Application.Selection;
            range.Find.ClearFormatting();
            range.Find.MatchCase = caseSensitive;
            range.Find.Text      = palavraBusca;
            range.Find.Wrap      = Word.WdFindWrap.wdFindAsk;

            range.Find.Execute();

            if (range.Find.Found)
            {
                range.Select();
                range.Text = palavraSubstituir;
                range.Select();
                range.SetRange(Globals.ThisAddIn.Application.Selection.End, documentoAtual.Content.End);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 23
0
        // 给 Word 文档中的数据表插入空行(注:表中已有一行空行~)
        #region InsertEmptyRowsToTable
        /// <summary>
        /// 给 Word 文档中的数据表插入空行(注:表中已有一行空行~)
        /// </summary>
        /// <param name="selection"></param>
        /// <param name="table"> word 文档中的表格 </param>
        /// <param name="docRowStart"> word 表格的起始行 </param>
        /// <param name="rowCount">要插入的空行数目</param>
        /// <param name="logInfo"> 日志内容 </param>
        /// <returns></returns>
        public static bool InsertEmptyRowsToTable(ref Word.Selection selection, ref Word.Table table,
                                                  int docRowStart, int docColStart, int rowCount, out string logInfo)
        {
            bool res = true;

            try
            {
                // 2012-01-10 Update
                if (rowCount > 1)
                {
                    table.Cell(docRowStart, docColStart).Select();
                    selection.InsertRowsBelow(rowCount - 1);
                    logInfo = "插入空行成功!";
                }
                else
                {
                    res     = false;
                    logInfo = "无对应的数据记录!";
                }
            }
            catch (Exception ex)
            {
                JCMsg.ShowErrorOK(ex.GetType().ToString() + "\n" + ex.Message);
                res     = false;
                logInfo = "插入空行失败!";
            }
            return(res);
        }
Ejemplo n.º 24
0
        private void OpenDocument(word.Application application)
        {
            word.Selection selection = application.Selection;
            if (selection == null)
            {
                MessageBox.Show(@"Selection is null");
                return;
            }

            switch (selection.Type)
            {
            case word.WdSelectionType.wdSelectionNormal:
            case word.WdSelectionType.wdSelectionIP:
            {
                var range = _document.Range();
                range.Select();
                richTextBox_Document.Text       = range.Text;
                TextParseManager.FullWordText   = range.Text;
                toolStripStatusLabel_Главы.Text = @"Главы: " + WordHelpers.FindChapters(_document);
                var array = WordHelpers.SplitByChapters(TextParseManager.FullWordText);
                break;
            }

            default:
                MessageBox.Show(@"Неподдерживаемый тип Selection");
                break;
            }

            _document.RemoveDocumentInformation(word.WdRemoveDocInfoType.wdRDIAll);
            application.Documents.Save(NoPrompt: true, OriginalFormat: true);
        }
Ejemplo n.º 25
0
        public bool FindNext(string text)
        {
            Word.Selection selecao    = Globals.ThisAddIn.Application.Selection;
            Word.Document  doc        = Globals.ThisAddIn.Application.ActiveDocument;
            Word.Selection selection  = Globals.ThisAddIn.Application.ActiveDocument.Application.Selection;
            Word.Find      findObject = Globals.ThisAddIn.Application.Selection.Find;

            object findText = text;

            selection.Find.ClearFormatting();
            selection.Find.Forward   = true;
            selection.Find.MatchCase = false;
            selection.Find.Execute(ref findText);

            if (!selection.Find.Found)
            {
                doc.Range(0, 0).Select();
                selection.Find.Execute(ref findText);
                if (!selection.Find.Found)
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 26
0
        public void app_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel)
        {
            if (null == selection)
            {
                return;
            }
            range = selection.Range;

            switch (selection.Type)
            {
            case Word.WdSelectionType.wdSelectionIP:
                range.Expand(Word.WdUnits.wdWord);                         // expand range to be a whole word
                break;

            case Word.WdSelectionType.wdSelectionNormal:                     // word(s) selected
                break;

            default: return;
            }
            // Trim range, so when we replace the query we don't trample on the spaces between words
            while (range.Characters.First.Text == " ")
            {
                range.MoveStart(Word.WdUnits.wdCharacter);
            }
            while (range.Characters.Last.Text == " ")
            {
                range.MoveEnd(Word.WdUnits.wdCharacter, -1);
            }

            if (!string.IsNullOrEmpty(range.Text))
            {
                ShowMenu(range.Text);
            }
        }
Ejemplo n.º 27
0
        public bool Start(string strFileName)
        {
            m_pApp       = null;
            m_pDoc       = null;
            m_pTable     = null;
            m_pSelection = null;

            old_table_index = 0;

            try
            {
                m_pApp = new MSWord.Application();

                if (strFileName == "")
                {
                    m_pDoc = m_pApp.Documents.Add();
                }
                else
                {
                    m_pDoc = m_pApp.Documents.Add(strFileName);
                }

                return(true);
            }
            catch (Exception ex)
            {
                MyLocalizer.XtraMessageBoxShow("В программе произошла ошибка. Описание: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(false);
        }
Ejemplo n.º 28
0
        private void remove_Click(object sender, RibbonControlEventArgs e)
        {
            Word.Selection currentSelection = Globals.ThisAddIn.Application.Selection;
            if (currentSelection.Start == currentSelection.End)
            {
                currentSelection.MoveRight(Word.WdUnits.wdCharacter, 1, Word.WdMovementType.wdExtend);
            }

            Word.Range currentRange = Globals.ThisAddIn.Application.Selection.Range;

            string          xmlstr   = currentRange.WordOpenXML;
            XDocument       doc      = XDocument.Parse(xmlstr);
            XNamespace      w        = doc.Descendants().First(x => x.Name.LocalName == "document").Name.Namespace;
            List <XElement> elements = doc.Descendants(w + "ruby").ToList();

            foreach (XElement ele in elements)
            {
                List <XElement> tproperties = ele.Descendants(w + "rubyBase").Single().Descendants(w + "rPr").ToList();
                XElement        t           = ele.Descendants(w + "rubyBase").Single().Descendants(w + "t").Single();
                ele.ReplaceWith(tproperties, t);
            }

            currentRange.InsertXML(doc.ToString());
            currentRange.Select();
        }
Ejemplo n.º 29
0
        public void SetCellsFont(int FirstColumn, int LastColumn, int FirstRow, int LastRow, string strName, int bold, float size, int indTable)
        {
            GetTableReference(indTable);

            MSWord.Cell pCellBegin = m_pTable.Cell(FirstRow, FirstColumn);
            MSWord.Cell pCellEnd   = m_pTable.Cell(LastRow, LastColumn);
            if (pCellBegin == null)
            {
                return;
            }
            if (pCellEnd == null)
            {
                return;
            }

            MSWord.Range range = m_pDoc.Range(pCellBegin.Range.Start, pCellEnd.Range.End);
            range.Select();
            MSWord.Selection sel = m_pApp.Selection;
            //MSWord.Font old_font = sel.Font;
            if (strName != "")
            {
                sel.Font.Name = strName;
            }
            if (bold != -1)
            {
                sel.Font.Bold = bold;
            }
            if (size > 0)
            {
                sel.Font.Size = size;
            }
            //sel.Font = old_font;
        }
Ejemplo n.º 30
0
        private void btn_ApplyBoilerplate_Click(object sender, RibbonControlEventArgs e)
        {
            //get the text from the settings
            Boilerplate bp = Properties.Settings.Default.newboiler;

            //Find out which option is selected
            RibbonDropDownItem item = this.dd_Boilerplate.SelectedItem;

            if (bp.Dict.ContainsKey(item.Label))
            {
                Word.Document  doc       = Globals.ThisAddIn.Application.ActiveDocument;
                Word.Selection selection = Globals.ThisAddIn.Application.Selection;
                if (selection != null && selection.Range != null)
                {
                    selection.Comments.Add(selection.Range, bp.Dict[item.Label].Text);
                }
                else
                {
                    MessageBox.Show("Could not find any selected text or valid insertion point. Please let Aaron know!");
                }
            }
            else
            {
                MessageBox.Show("An error occurred when finding your boilerplate. Please let Aaron know!");
                return;
            }
        }
Ejemplo n.º 31
0
 public void app_WindowBeforeRightClick(Word.Selection selection, ref bool Cancel)
 {
     if (selection != null && !string.IsNullOrEmpty(selection.Text))
     {
         string text = selection.Text;
         currentSelection = selection;
         ShowMenu(text.Trim());
     }
 }
Ejemplo n.º 32
0
        // Display suggestion box on screen
        private void displaySuggestionBox()
        {
            Word.Selection currentSelection = Application.Selection;

            currentSelection = Application.Selection;

            Point caretPosition = evaluateCaretPosition();
            caretPosition = calculateSuggestionBoxPosition(caretPosition);
            autoCompleteForm.SetDesktopLocation(caretPosition.X, caretPosition.Y);
            autoCompleteForm.Visible = true;
        }
Ejemplo n.º 33
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            _dispatcher = Dispatcher.CurrentDispatcher;

            SetKeyboardHook();
            SetMouseHook();

            // Track the handle ID for the text editor (Microsoft Word)
            int handle = (int) GetActiveWindow();
            currentSelection = Application.Selection;

            // Initialize forms and set Microsoft Word as the parent window
            autoCompleteForm = new AutoCompleteForm();
            notificationForm = new Notification();
            extendSuggestionForm = new ExtendSuggestionHint();

            Application.WindowActivate += new Word.ApplicationEvents4_WindowActivateEventHandler(Application_WindowActivate);
            Application.WindowDeactivate += new Word.ApplicationEvents4_WindowDeactivateEventHandler(Application_WindowDeactivate);
            Application.WindowSize += new Microsoft.Office.Interop.Word.ApplicationEvents4_WindowSizeEventHandler(OnWindowSizeChange);

            //Convert Words DPI based Height and Width
            System.Drawing.Graphics g = notificationForm.CreateGraphics();
            dpi = g.DpiX;

            updateApplicationSizeDetail();

            logic = new Client();

            bool serverStatus = initConfiguration();
            extMode = new ExtensionMode(logic);

            if (serverStatus)
            {
                tourForm = new Tour(this.config, configurationFilePath);
                if (tourEnabled)
                {
                    tourForm.ShowDialog();
                }
            }
            else
            {
                // Setting this to true allow ACP to inform user that ACP is not been running
                isDisablePopUp = true;
            }

            // for user testing
            startTestTime = "START TIME," + DateTime.Now.ToString("HH:mm:ss") + "\r";
        }
Ejemplo n.º 34
0
        private void Application_WindowActivate(Word.Document Doc, Word.Window Wn)
        {
            // for User Testing
            endSwitchTime = DateTime.Now;
            appendSwitchWindowString();

            // Track the handle ID for the text editor (Microsoft Word)
            int tempHandle = (int)GetActiveWindow();
            if (handle != tempHandle)
            {
                handle = (int)GetActiveWindow();
                currentSelection = Application.Selection;

                // Retrieve handle of the Microsoft Word window.
                wordMain = new NativeWindow();
                wordMain.AssignHandle(new IntPtr(handle));

                // Hide the form off the screen
                autoCompleteForm.Location = new Point(-1000, -1000);
                notificationForm.Location = new Point(-1000, -1000);
                extendSuggestionForm.Location = new Point(-1000, -1000);

                // Reassign forms' parent
                autoCompleteForm.Visible = false;
                autoCompleteForm.showForm(wordMain); // Assign the form parent to the current active window
                autoCompleteForm.Focus(); // In order to make the child form appear infront of the parent form
                autoCompleteForm.Hide();

                notificationForm.Visible = false;
                notificationForm.Show(wordMain); // Assign the form parent to the current active window
                notificationForm.Focus(); // In order to make the child form appear infront of the parent form
                notificationForm.Hide();

                extendSuggestionForm.Visible = false;
                extendSuggestionForm.Show(wordMain);
                extendSuggestionForm.Focus();
                extendSuggestionForm.Hide();

                wordMain.ReleaseHandle();
            }

            if (!isEnabled && isDisablePopUp)
            {
                Globals.ThisAddIn.Dispatcher.Invoke(new displayMessageDelegate(displayMessage), new Object[] { ERROR_CONNECTION });

                // Disable the pop-up
                isDisablePopUp = false;
            }

            BackgroundWorker b = new BackgroundWorker();
            b.DoWork += delegate(object sender2, DoWorkEventArgs e2)
            {
                try
                {
                    if (isEnabled)
                    {
                        // Inform ACP to change destination document
                        logic.setDestinationDocument(handle);
                    }
                }
                catch (SocketException e)
                {
                    Globals.ThisAddIn.Dispatcher.Invoke(new displayMessageDelegate(displayMessage), new Object[] { ERROR_CONNECTION });
                    markServerDown();
                }
            };
            b.RunWorkerAsync();

            updateApplicationSizeDetail();
            SetActiveWindow(new IntPtr(tempHandle));
        }