Exemple #1
0
        /// <summary>
        /// 向 Word 文件中添加单张图片
        /// </summary>
        /// <param name="variableName">word 模版中的变量</param>
        /// <param name="fileFullName">图片文件的全路径名</param>
        /// <param name="width">图片宽度</param>
        /// <param name="height">图片高度</param>
        public void AddPictures(string variableName, List <string> fileFullNames, int width, int height)
        {
            //object replaceAll = Word.WdReplace.wdReplaceAll;
            wApp.Options.ReplaceSelection         = true;
            wApp.Selection.Find.Forward           = true;
            wApp.Selection.Find.Wrap              = Word.WdFindWrap.wdFindContinue;
            wApp.Selection.Find.Format            = false;
            wApp.Selection.Find.MatchCase         = false;
            wApp.Selection.Find.MatchWholeWord    = false;
            wApp.Selection.Find.MatchByte         = true;
            wApp.Selection.Find.MatchWildcards    = false;
            wApp.Selection.Find.MatchSoundsLike   = false;
            wApp.Selection.Find.MatchAllWordForms = false;
            wApp.Selection.Find.ClearFormatting();
            wApp.Selection.Find.Text             = variableName;
            wApp.Selection.Find.Replacement.Text = "";

            wApp.Selection.Find.Execute(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);


            foreach (var fileFullName in fileFullNames)
            {
                Word.InlineShape rang = wApp.Selection.InlineShapes.AddPicture(fileFullName,
                                                                               ref missing, ref missing, ref missing);
                rang.Width  = width;
                rang.Height = height;
                rang.Reset();
            }
        }
        protected void AddChart(int chartNumber, string[,] data)
        {
            Word.InlineShape inlineShape = _document.Content.InlineShapes[chartNumber];

            object oRngTarget = _wordApp.Selection.Range;
            object oOLEClass  = "Excel.Sheet.12";

            Word.InlineShape ils = _document.InlineShapes.AddOLEObject(ref oOLEClass, ref missing, ref missing,
                                                                       ref missing, ref missing, ref missing, ref missing, ref oRngTarget);
            Word.OLEFormat olef = ils.OLEFormat;

            //if (inlineShape.OLEFormat.ProgID == "Excel.Chart.12")
            //{
            //inlineShape.Activate();
            Excel.Workbook  wb = (Excel.Workbook)olef.Object;
            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];

            for (int i = 0; i < data.GetLength(0); i++)
            {
                for (int j = 0; j < data.GetLength(1); j++)
                {
                    ((Excel.Range)ws.Cells[i + 1, j + 1]).Value = data[i, j];
                }
            }
            //}
            //ReplaceText("$picture1.1$", inlineShape);
            Marshal.ReleaseComObject(ils);
        }
        private static void FillRangeByReceiveInfo(Word.Document dct, Word.Bookmark bookMark,
                                                   string userId, string userName)
        {
            if (userId == string.Empty)
            {
                return;
            }

            string signFileName = GetStaffSignFileName(userId);

            if (signFileName == string.Empty)
            {
                //如果没有下载到签名文件,则填写姓名
                bookMark.Range.Text = userName;
            }
            else
            {
                object range = bookMark.Range;

                Word.InlineShape shape = dct.InlineShapes.AddPicture(signFileName,
                                                                     false, true, ref range);
                shape.Width  = XUICommon.SystemConfigInfo.SignWidht;
                shape.Height = XUICommon.SystemConfigInfo.SignHeight;
            }
        }
Exemple #4
0
 /// <summary>
 /// 设置页眉
 /// </summary>
 /// <param name="wordApp">传入WordApp</param>
 /// <param name="wordDoc">传入WordDoc</param>
 private static void AddPageHeaderFooter(MSWord.Application wordApp, MSWord.Document wordDoc)
 {
     try
     {
         Bitmap png = Pic.pic;
         png.Save(Path.GetTempPath() + "\\pic.png");
         if (wordApp.ActiveWindow.ActivePane.View.Type == MSWord.WdViewType.wdNormalView ||
             wordApp.ActiveWindow.ActivePane.View.Type == MSWord.WdViewType.wdOutlineView)
         {
             wordApp.ActiveWindow.ActivePane.View.Type = MSWord.WdViewType.wdPrintView;
         }
         wordApp.ActiveWindow.View.SeekView            = MSWord.WdSeekView.wdSeekCurrentPageHeader;
         wordApp.Selection.HeaderFooter.LinkToPrevious = false;
         MSWord.InlineShape il =
             wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(Path.GetTempPath() + "\\pic.png",
                                                                               ref _nothing, ref _nothing, ref _nothing);
         il.ScaleHeight = 134f;
         il.ScaleWidth  = 238f;
         wordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment =
             MSWord.WdParagraphAlignment.wdAlignParagraphRight;
         wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;
     }
     catch (Exception)
     {
         ed.WriteMessage("\n设置Word页面发生未知错误,程序中断。如需帮助请联系作者。");
         wordApp.Quit(ref _nothing, ref _nothing, ref _nothing);
     }
 }
Exemple #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            word.Application app = new word.Application();
            app.Visible = true;

            CommandBar pdbar = app.CommandBars.Add("prontodoc link");


            CommandBarButton ctrl = pdbar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true) as CommandBarButton;

            ctrl.Tag     = "test";
            ctrl.Caption = "Add ProntoDoc link";
            //ctrl.Style = MsoButtonStyle.msoButtonIconAndCaption;
            ctrl.Visible = true;
            //ctrl.Click += new _CommandBarButtonEvents_ClickEventHandler(ctrl_Click);
            // ctrl.OnAction
            pdbar.Visible = true;


            word.Document    doc = app.Documents.Open(@"e:\Doc1.docx");
            word.InlineShape img = doc.InlineShapes[1];


            string link = img.Hyperlink.Address;

            MessageBox.Show("old link: " + link);
            img.Hyperlink.Address = "http://localhost:81/";
            doc.Save();
            doc.Close();
            app.Quit();
        }
Exemple #6
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);
        }
        private void btnInsert_Click(object sender, EventArgs e)
        {
            float    charsize = (float)numericUpDown1.Value; //磅为单位(1/72英寸)
            Graphics gs       = imgChar.CreateGraphics();
            Metafile mf       = new Metafile(Globals.ThisDocument.Path + "\\meta.emf", gs.GetHdc(), EmfType.EmfOnly);
            Graphics g        = Graphics.FromImage(mf);
            Notation nota     = Notation.processString(txtNotation.Text);

            nota.characterize(charsize * g.DpiY / 72);  //磅换成像素
            nota.draw(g, (float)UpDownThin.Value * 0.01f * charsize * g.DpiY / 72,
                      (float)UpDownThick.Value * 0.01f * charsize * g.DpiY / 72);
            g.Dispose();
            GraphicsUnit charunit = GraphicsUnit.Point;
            RectangleF   charrect = mf.GetBounds(ref charunit); //获得图像边界大小

            mf.Dispose();
            gs.Dispose();
            Word.InlineShape shape = Globals.ThisDocument.InlineShapes.AddPicture(Globals.ThisDocument.Path + "\\meta.emf");
            if (shape.Height > charsize)    //限定高度,超过则等比缩放
            {
                shape.Width  = shape.Width / shape.Height * charsize;
                shape.Height = charsize;
            }
            Globals.ThisDocument.Application.Selection.Move(Word.WdUnits.wdCharacter, 1);   //光标往后移一格
            if (File.Exists(Globals.ThisDocument.Path + "\\meta.emf"))
            {
                File.Delete(Globals.ThisDocument.Path + "\\meta.emf");
            }
        }
Exemple #8
0
        //word对象特征
        public string wordObject_value(Word.Range range)
        {
            wordObject = "null";
            if (range.InlineShapes.Count != 0)
            {
                Word.InlineShape shape = range.InlineShapes[1];

                if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture && range.Text.Trim().Length <= 2)//判断是否为图片
                {
                    wordObject = "图对象";
                }
                else if (shape.Type == Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject && range.Text.Trim().Length <= 2)//判断是否为图片
                {
                    wordObject = "公式对象";
                }
            }
            else if (range.Comments.Count >= 1 && range.Comments[1].Range.Text == "表格")
            {
                wordObject = "表对象";//判断是否为表格
            }
            else if (range.OMaths.Count > 0)
            {
                wordObject = "公式对象";//判断是否为公式对象
            }
            return(wordObject);
        }
Exemple #9
0
        public static void UpdateGraph1(string outputPath, double[] lastValues, double[] currentValues, int graphIndex)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            app.Visible       = false;
            object missing      = System.Reflection.Missing.Value;
            object templateName = outputPath;                                   //最终的word文档需要写入的位置
            object ModelName    = outputPath;                                   //word  模板的位置
            object count        = 1;
            object WdLine       = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行;


            Microsoft.Office.Interop.Word.Document wordDoc = app.Documents.Open(ref ModelName, 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);//打开word模板

            string[] titles     = { "日期", "本周", "上周" };
            string[] names      = { "周五", "周六", "周日", "周一", "周二", "周三", "周四" }; // 数据名称
            int      fieldCount = names.Length;

            try
            {
                Microsoft.Office.Interop.Word.InlineShape shape = wordDoc.InlineShapes[graphIndex];
                Microsoft.Office.Interop.Word.Chart       chart = shape.Chart;
                chart.ChartData.Activate();
                Microsoft.Office.Interop.Excel.Worksheet book = chart.ChartData.Workbook.Worksheets["Sheet1"];

                var data = new object[fieldCount, 3];
                for (int i = 0; i < fieldCount; i++)
                {
                    data[i, 0] = names[i];
                    data[i, 1] = currentValues[i];
                    data[i, 2] = lastValues[i];
                }
                book.get_Range("A2", "C" + (fieldCount + 1)).Value = data;
                book.get_Range("A1", "C1").Value = titles;
                ((Microsoft.Office.Interop.Excel.Range)book.Cells[1, titles.Length + 1]).Select();
                ((Microsoft.Office.Interop.Excel.Range)book.Cells[1, titles.Length + 1]).EntireColumn.Delete(0);

                book.Application.DisplayAlerts = false;
                book.Application.Quit();

                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;//保存格式
                wordDoc.SaveAs(ref templateName, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            catch
            {
            }
            finally
            {
                //关闭wordDoc,wordApp对象
                object SaveChanges    = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;
                object OriginalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdWordDocument;
                object RouteDocument  = false;
                wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
                app.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
            }
        }
 protected void PasteImage(string imagePath, string bookmark)
 {
     Word.Range range = _document.Bookmarks.get_Item(bookmark).Range;
     range.Text = "";
     Word.InlineShape inlineShape = _document.InlineShapes.AddPicture(imagePath, Range: range);
     //inlineShape.Width = 400;
     inlineShape.Height = 250;
 }
 private void InsertLine()
 {
     Word.InlineShape line = document.Paragraphs.Last.Range.InlineShapes.AddHorizontalLineStandard(ref missing);
     line.Height = 2;
     line.Fill.Solid();
     line.HorizontalLineFormat.NoShade      = true;
     line.Fill.ForeColor.RGB                = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
     line.HorizontalLineFormat.PercentWidth = 100;
     line.HorizontalLineFormat.Alignment    = Word.WdHorizontalLineAlignment.wdHorizontalLineAlignCenter;
 }
Exemple #12
0
        public void AddPicHeader(string img, Word.WdParagraphAlignment align)
        {
            m_WordDoc.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
            Word.InlineShape il = m_WordDoc.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(
                img, ref missing, ref missing, ref missing);

            il.Width  = 20;
            il.Height = 20;

            il.HorizontalLineFormat.Alignment = Word.WdHorizontalLineAlignment.wdHorizontalLineAlignRight;
        }
Exemple #13
0
        /// <summary>
        /// 插入图片 
        /// </summary>
        /// <param name="bookmark">位置标签</param>
        /// <param name="picturePath">图片路径</param>
        /// <param name="width">图片宽度(cm)</param>
        /// <param name="height">图片高度(cm)</param>

        public void InsertPicture(string bookmark, string picturePath, float width, float height)
        {
            object oBookmark        = bookmark;                                     //WORD中预定义的书签
            Object linkToFile       = false;                                        //图片是否为外部链接 
            Object saveWithDocument = true;                                         //图片是否随文档一起保存  
            object range            = oDoc.Bookmarks.get_Item(ref oBookmark).Range; //图片插入位置 

            Word.InlineShape shape = oWord.ActiveDocument.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
            shape.Width = oWord.CentimetersToPoints(width);;      //设置图片宽度             
            shape.Height = oWord.CentimetersToPoints(height);;    //设置图片高度   
            // oDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape().WrapFormat.Type = Word.WdWrapType.wdWrapNone;//设置环绕的方式
        }
        /// <summary>
        /// Updates a specific field with data from the object
        /// </summary>
        /// <param name="client">The object you want the data to come from</param>
        /// <param name="field">The field to be updated</param>
        /// <param name="properties">A list of the properties of the object, if null it will ascertain</param>
        public static void UpdateMergeField(object client, Field field, List <PropertyInfo> properties = null)
        {
            if (properties == null)
            {
                properties = client.GetType().GetProperties().ToList();
            }
            MergeField mergeField = GetMergeFieldData(field);

            if (mergeField.Name != "")
            {
                foreach (var prop in properties)
                {
                    if (prop.Name.ToUpper() == mergeField.Name.ToUpper())
                    {
                        try
                        {
                            field.Select();
                            if (prop.PropertyType.Name == "Decimal")
                            {
                                decimal value = Decimal.Parse(prop.GetValue(client, null).ToString());
                                app.Selection.TypeText(String.Format("{0:0.00}", value));
                            }
                            else if (mergeField.Type.ToUpper() == "IMAGE")
                            {
                                app.Selection.TypeText(" ");
                                string imageLocation = prop.GetValue(client, null).ToString();
                                Range  range         = app.Selection.Range;
                                Microsoft.Office.Interop.Word.InlineShape shape = range.InlineShapes.AddPicture(imageLocation);
                                shape.LockAspectRatio = MsoTriState.msoTrue;
                                if (mergeField.Parameters.TryGetValue("height", out string sHeight))
                                {
                                    try
                                    {
                                        shape.Height = float.Parse(sHeight);
                                    }
                                    catch
                                    {
                                        throw new Exception("Height was not an float value");
                                    }
                                }
                            }
                            else
                            {
                                app.Selection.TypeText(prop.GetValue(client, null).ToString());
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Exemple #15
0
        public static void UpdateGraph2(string outputPath, string[] names, double[] currentValues, int graphIndex)
        {
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            app.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
            app.Visible       = false;
            object missing      = System.Reflection.Missing.Value;
            object templateName = outputPath;                                   //最终的word文档需要写入的位置
            object ModelName    = outputPath;                                   //word  模板的位置
            object count        = 1;
            object WdLine       = Microsoft.Office.Interop.Word.WdUnits.wdLine; //换一行;


            Microsoft.Office.Interop.Word.Document wordDoc = app.Documents.Open(ref ModelName, 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);//打开word模板


            try
            {
                int fieldCount = names.Length;
                Microsoft.Office.Interop.Word.InlineShape shape     = wordDoc.InlineShapes[graphIndex];
                Microsoft.Office.Interop.Word.OLEFormat   oleformat = shape.OLEFormat;
                oleformat.Open();
                Microsoft.Office.Interop.Graph.Chart chart = (Microsoft.Office.Interop.Graph.Chart)(oleformat.Object);
                chart.Application.DataSheet.Cells.ClearContents();
                chart.Application.DataSheet.Cells.set_Item(1, "", "名称");
                for (int i = 0; i < names.Length; i++)
                {
                    chart.Application.DataSheet.Cells.set_Item(i + 2, "", names[i]);
                    chart.Application.DataSheet.Cells.set_Item(i + 2, "A", currentValues[i]);
                }
                chart.Application.Update();
                chart.Application.DisplayAlerts = false;
                chart.Application.Quit();

                object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault;//保存格式
                wordDoc.SaveAs(ref templateName, ref format, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
            }
            catch
            {
            }
            finally
            {
                //关闭wordDoc,wordApp对象
                object SaveChanges    = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;
                object OriginalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdWordDocument;
                object RouteDocument  = false;
                wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
                app.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
            }
        }
            public Word.Document AddFooterImage(Word.Document document, string imagePath)
            {
                object tr = true;
                object fa = false;

                foreach (Word.Section section in document.Sections)
                {
                    Word.Range       footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                    Word.InlineShape picture     = document.InlineShapes.AddPicture(imagePath, tr, fa, footerRange);
                }

                return(document);
            }
Exemple #17
0
        /// <summary>
        /// 导出visio的Page中的所有形状到word中
        /// </summary>
        /// <param name="Page">要进行粘贴的Visio中的页面</param>
        /// <param name="range">此时word文档中的全局range的位置或者范围</param>
        /// <remarks>在此方法中,会将visio指定页面中的所有形状进行选择,然后进行组合,最后将其输出到word中;
        /// 由局部安全的原则,在进行绘图前,将另起一行,并将段落样式设置为“图片”样式</remarks>
        private void Export_VisioPlanview(Page Page, ref Word.Range range)
        {
            Microsoft.Office.Interop.Visio.Application app = Page.Application;
            //
            Window wnd = default(Window);

            wnd      = app.ActiveWindow;
            wnd.Page = Page;


            wnd.Activate();
            //这里要将ShowChanges设置为True,否则下面的SelectAll()方法会被禁止。
            app.ShowChanges = true;
            wnd.SelectAll();
            //  ---------------------- 耗时代码1:复制Visio的Page中的所有形状
            //而且在这一步的时候Visio的窗口中可能会弹出子窗口
            wnd.Selection.Copy();
            //这一步也可能会导致Visio的窗口中弹出子窗口
            wnd.DeselectAll();

            //关闭所有的子窗口
            //Debug.Print(app.ActiveWindow.Windows.Count)     ‘即使只显示出一个子窗口,这里也会返回10
            //For Each subWnd As Visio.Window In app.ActiveWindow.Windows
            //    subWnd.Visible = False
            //Next

            //根据实际情况:每次都只弹出“外部数据”这一子窗口,所以在这里就只对其进行单独隐藏。
            wnd.Windows.ItemFromID((Int32)Visio.VisWinTypes.visWinIDExternalData).Visible = false;

            //让窗口的显示适应页面
            wnd.ViewFit = (Int32)Visio.VisWindowFit.visFitPage;
            Word.Range with_2 = range;
            //新起一行,并设置新段落的段落样式为图片
            NewLine(range, ParagraphStyle.picture);

            //  ---------------------- 耗时代码2:将Visio的Page中的所有形状粘贴到Word中(不可以用:DataType:=23)
            with_2.PasteSpecial(DataType:  Word.WdPasteDataType.wdPasteOLEObject, Placement: Word.WdOLEPlacement.wdInLine);


            Word.InlineShape shp = default(Word.InlineShape);
            range.Select();
            range.Application.Selection.MoveLeft(Unit: Word.WdUnits.wdCharacter, Count: 1,
                                                 Extend: Word.WdMovementType.wdExtend);
            shp = range.Application.Selection.InlineShapes[1];
            //约束图形的宽度,将其限制在word页面的正文宽度之内
            WidthRestrain(shp, ContentWidth);

            //刷新visio屏幕
            app.ShowChanges = true;
        }
        void BuildFramerateAnalysis(Excel._Workbook oWB, Word.Document oDoc, GetBucketValue grv, string uniqueName, string bookmarkName, float k_ignoreTime, int maxFPS)
        {
            const float k_fpsSize = 400.0f;
            const float aspect    = 3.0f / 4.0f;

            Excel._Worksheet oSheet = AddWorksheet(oWB, uniqueName);
            FillBuckets(oSheet, grv, 0, maxFPS, k_ignoreTime);
            Excel._Chart oChart = MakeChart(oWB, oSheet.get_Range("C1", "D61"), Excel.XlChartType.xlXYScatterSmoothNoMarkers, Excel.XlRowCol.xlColumns, 1, 0, false);
            SetupAxes(oChart, "Frame Rate", 0.0f, maxFPS, "Percentage of Time Below", 0.0f, -1.0f);
            Word.InlineShape oShape = InsertChart(oChart, oDoc, uniqueName + "acc", bookmarkName, k_fpsSize, k_fpsSize * aspect, 0.5f);
            oChart = MakeChart(oWB, oSheet.get_Range("A1", "B61"), Excel.XlChartType.xlXYScatterSmoothNoMarkers, Excel.XlRowCol.xlColumns, 1, 0, false);
            SetupAxes(oChart, "Frame Rate", 0.0f, maxFPS, "Percentage of Time", 0.0f, -1.0f);
            oShape = InsertChart(oChart, oDoc, uniqueName, bookmarkName, k_fpsSize, k_fpsSize * aspect, 0.5f);
        }
Exemple #19
0
        internal void InsertTable(int tableRow, int tableColumn, List <string> imagePaths)
        {
            wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
            MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
                                                    tableRow, tableColumn, ref Nothing, ref Nothing);

            //默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
            table.Borders.Enable = 0;//这个值可以设置得很大,例如5、13等等

            //表格的索引是从1开始的。
            for (int i = 1; i <= tableRow; i++)
            {
                for (int j = 1; j <= tableColumn; j++)
                {
                    int index = (i - 1) * tableColumn + j - 1;
                    if (index < imagePaths.Count)                                //有文件
                    {
                        string             FileName         = imagePaths[index]; //图片所在路径
                        object             LinkToFile       = false;
                        object             SaveWithDocument = true;
                        object             Anchor           = table.Cell(i, j).Range;//选中要添加图片的单元格
                        MSWord.InlineShape il = wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

                        //图片大小
                        il.Width  = 100;                                                    //图片宽度
                        il.Height = 100;                                                    //图片高度
                        table.Rows[i].Cells[j].Split(2, 1);
                        table.Cell(i + 1, j).Range.Text = "图片名称:" + (index + 1).ToString(); //
                        table.Cell(i + 1, j).Merge(table.Cell(i, j));                       //纵向合并
                    }
                }
            }
            //设置table样式
            table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;       //高度规则是:行高有最低值下限?
            table.Rows.Height     = wordApp.CentimetersToPoints(float.Parse("0.8")); //

            table.Range.Font.Size = 10.5F;
            table.Range.Font.Bold = 0;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;       //表格文本居中
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom; //文本垂直贴到底部
            //设置table边框样式
            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;                              //表格外框是双线
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleNone;                              //表格内框是单线

            table.Rows[1].Range.Font.Bold    = 1;                                                             //加粗
            table.Rows[1].Range.Font.Size    = 12F;
            table.Cell(1, 1).Range.Font.Size = 10.5F;
        }
Exemple #20
0
        /// <summary>
        /// Redact an inline shape by replacing it with a 1px image.
        /// </summary>
        /// <param name="InlineShape">The InlineShape to redact.</param>
        private void RedactInlineShape(Word.InlineShape InlineShape)
        {
            string ImagePath = RedactCommon.CreateRedactedImage();

            float Height = InlineShape.Height;
            float Width  = InlineShape.Width;

            InlineShape.Range.Select();
            Application.Selection.Delete(ref Missing, ref Missing);

            Word.InlineShape RedactedImage = Application.Selection.InlineShapes.AddPicture(ImagePath, ref Missing, ref Missing, ref Missing);
            RedactedImage.AlternativeText = string.Empty;
            RedactedImage.Height          = Height;
            RedactedImage.Width           = Width;
        }
Exemple #21
0
        /// <summary>
        /// 图片书签替换实例的实现
        /// </summary>
        /// <param name="data"></param>
        public override void Instantiate(object data)
        {
            string path = data.ToString();

            //issue: 修正当图片文件不存在时导致整个文档转换失败的BUG
            if (!File.Exists(path))
            {
                return;
            }
            Select();
            object objTrue = true, objFalse = false, objMissing = Type.Missing;

            Word.InlineShape shape = Document.Application.Selection.InlineShapes.AddPicture(path, ref objTrue, ref objTrue, ref objMissing);
            shape.ConvertToShape().WrapFormat.Type = Word.WdWrapType.wdWrapFront;
        }
        Word.InlineShape InsertChart(Excel._Chart oChart, Word.Document oDoc, string filename, string placementName, float width, float height, float scale)
        {
            object oMissing = Missing.Value;
            string filepath = System.IO.Path.GetTempPath() + filename + ".png";

            oChart.ChartArea.Width  = width;
            oChart.ChartArea.Height = height;
            oChart.Export(filepath, "png", false);
            object oEndOfDoc = placementName;

            Word.Range       insertPoint = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            Word.InlineShape oShape      = insertPoint.InlineShapes.AddPicture(filepath, ref oMissing, ref oMissing, ref oMissing);
            oShape.Width  = width * scale;
            oShape.Height = height * scale;
            return(oShape);
        }
        public void TakeScreenshot()
        {
            try
            {
                String stepType = ScenarioStepContext.Current.StepInfo.StepDefinitionType.ToString();
                if (stepType.Equals("Then", StringComparison.InvariantCultureIgnoreCase) &&
                    IsObjectEvidenceTagExists())
                {
                    String scenarioTitle = ScenarioContext.Current.ScenarioInfo.Title;
                    String step          = ScenarioContext.Current.StepContext.StepInfo.Text;

                    ITakesScreenshot takesScreenshot    = BrowserUtilities.WebDriver as ITakesScreenshot;
                    Screenshot       screenShot         = takesScreenshot.GetScreenshot();
                    String           screenshotFullPath = FeatureContext.Current["Screenshot_TempFolder"] + "\\temp.png";
                    screenShot.SaveAsFile(screenshotFullPath);

                    Word.Application application = new Word.Application();
                    application.Visible = false;
                    Word.Document doc = application.Documents.Open(FeatureContext.Current["ReportsFolderPath"].ToString() + FeatureContext.Current["OELog"].ToString() + ".docx");

                    Word.Table table = doc.Tables[2];
                    table.Rows.Add(System.Reflection.Missing.Value);
                    int lastRowIndex = table.Rows.Count;
                    table.Rows[lastRowIndex].Range.Bold = 1;
                    String text = "STEP " + FeatureContext.Current["StepNumber"];
                    text += "\n Scenario: " + scenarioTitle + ", ScenarioStep: " + step + ", Date: " + DateTime.Now.ToString();
                    table.Cell(lastRowIndex, 1).Range.Text      = text;
                    table.Cell(lastRowIndex, 1).Range.Font.Size = 11;
                    table.Cell(lastRowIndex, 1).Range.Font.Name = "Times New Roman";

                    table.Rows.Add(System.Reflection.Missing.Value);
                    lastRowIndex = table.Rows.Count;
                    Word.InlineShape image = table.Cell(lastRowIndex, 1).Range.InlineShapes.AddPicture(screenshotFullPath);
                    image.Width  = 500;
                    image.Height = 300;
                    doc.Save();
                    File.Delete(screenshotFullPath);

                    doc.Save();
                    doc.Close();
                    application.Quit();
                }
            }
            catch (Exception e)
            {
            }
        }
Exemple #24
0
        public static void MakingViaConfig(WordConfig config)
        {
            Word.Range range;
            object     saveWithDocument = true;
            object     missing          = Type.Missing;

            Word.Application app = new Word.Application();
            app.Visible = true;
            Word.Document doc = app.Documents.Open(config.TemplateFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);

            foreach (PicBookmark item in config.ListPicBookmark)  //图片书签
            {
                object bookmark = item.Bookmark;
                range = doc.Bookmarks.get_Item(ref bookmark).Range;
                Word.InlineShape pic = doc.InlineShapes.AddPicture(item.PicFileName, ref missing, ref saveWithDocument, range);
                float            sc  = 380 / pic.Width;
                pic.Width  = 380;
                pic.Height = pic.Height * sc;

                if (item.ListTextBox != null)
                {
                    foreach (TextBoxOnPic tb in item.ListTextBox)
                    {
                        Word.Shape text = doc.Shapes.AddTextbox(Core.MsoTextOrientation.msoTextOrientationHorizontal, tb.Left, tb.Top, tb.Width, tb.Height);
                        text.Line.Visible = Core.MsoTriState.msoFalse;  //无边框
                        text.TextFrame.ContainingRange.Text = tb.Text;
                        text.TextFrame.TextRange.Font.Size  = tb.Size;
                        text.TextFrame.TextRange.Font.Bold  = tb.Bold;
                        text.TextFrame.TextRange.Font.Name  = tb.FontName;
                        text.TextFrame.TextRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        text.ZOrder(Core.MsoZOrderCmd.msoBringToFront);
                    }
                }
            }

            foreach (TextBookmark item in config.ListTextBookmark)  //文字书签
            {
                object bookmark = item.Bookmark;
                range      = doc.Bookmarks.get_Item(ref bookmark).Range;
                range.Text = item.Text;
            }

            doc.SaveAs2(config.OutFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            //app.Quit();
        }
Exemple #25
0
        public static void Graphics(List <DataPoint> Values, string chartName = null, string legend = null, excel.XlChartType type = excel.XlChartType.xlColumnClustered)
        {
            if (Values.Count == 0)
            {
                return;
            }

            try
            {
                Supports.GetProfileForm().ChangeState();
                word.Application app = new word.Application();
                app.Visible = true;
                Thread.Sleep(500);
                var doc = app.Documents.Add();


                word.InlineShape chartShape = doc.InlineShapes.AddOLEObject((Microsoft.Office.Core.XlChartType)type);
                chartShape.AlternativeText = "Chart1";
                word.Chart chart = chartShape.OLEFormat.Object as word.Chart;
                dynamic    book  = chart.ChartData.Workbook;
                //dynamic bookTable = book.Sheets[1].ListObjects("Table1");
                //bookTable.DataBodyRange.ClearContents();
                //Thread.Sleep(500);
                //excel.Chart chart =  exApp.Charts[0];
                //chart.SetSourceData(exApp.Cells.Range["A2", "E15"]);
                //exApp.Cells.Range["A2", "E5"].Clear();
                //sheert.ListObjects.Item[1].Resize(sheert.Range["A1", "B" + (Values.Count + 1).ToString()]);
                //sheert.Cells[1, 2] = legend;

                for (var i = 2; i < Values.Count + 2; i++)
                {
                    //exApp.Cells[i, 1] = DateTime.FromOADate(Values[i - 2].XValue);
                    //exApp.Cells[i, 2] = Values[i - 2].YValues[0];
                }
            }
            catch (Exception e)
            {
                MessageBoxTi.Show("Documentation.Graphics " + e.Message);
                return;
            }
            finally
            {
                Supports.GetProfileForm().ChangeState(true);
            }
        }
Exemple #26
0
        public static void ReplaceImage(Tuple <OpWord.Application, OpWord.Document> doc, string strTag, string strPictureFileName)
        {
            object nullobj = Type.Missing;

            object objReplace = OpWord.WdReplace.wdReplaceAll;

            OpWord.Selection selection = doc.Item1.Selection;

            object unite = OpWord.WdUnits.wdStory;

            selection.Find.Text = strTag;

            //  selection.Find.Replacement.Text = "";
            selection.Find.Execute();
            //selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
            //                          ref nullobj, ref nullobj, ref nullobj,
            //                          ref nullobj, ref nullobj, ref nullobj,
            //                          ref nullobj, ref objReplace, ref nullobj,
            //                          ref nullobj, ref nullobj, ref nullobj);

            //  selection.EndKey(ref unite, ref nullobj);

            //定义该插入的图片是否为外部链接
            Object linkToFile = false;               //默认,这里貌似设置为bool类型更清晰一些
            //定义要插入的图片是否随Word文档一起保存
            Object saveWithDocument = true;          //默认

            Object range = selection.Range;

            OpWord.InlineShape inlineShape = doc.Item2.InlineShapes.AddPicture(strPictureFileName, ref linkToFile, ref saveWithDocument, ref range);

            //设置图片大小
            inlineShape.Width  = 100;
            inlineShape.Height = 100;

            selection.Find.Text             = strTag;
            selection.Find.Replacement.Text = "";
            selection.Find.Execute(ref nullobj, ref nullobj, ref nullobj,
                                   ref nullobj, ref nullobj, ref nullobj,
                                   ref nullobj, ref nullobj, ref nullobj,
                                   ref nullobj, ref objReplace, ref nullobj,
                                   ref nullobj, ref nullobj, ref nullobj);

            //  doc.Item2.Save();
        }
        /// <summary>
        /// gets and returns the selected image
        /// </summary>
        public static Word.InlineShape GetSelectedShape()
        {
            Word.InlineShape shape = null;
            try
            {
                if (!(activeSelection.Range.InlineShapes[1] is null))
                {
                    shape = activeSelection.Range.InlineShapes[1];
                    activeSelection.ChildShapeRange.WrapFormat.Type = Word.WdWrapType.wdWrapThrough;
                }
            }
            catch (System.Runtime.InteropServices.COMException e)
            {
                MessageBox.Show(e.Message);
            }

            return(shape);
        }
Exemple #28
0
        private string ImportPdeChart(Word.Document wDoc, string chartName, string chartContent)
        {
            string chartPath = AssetManager.FileAdapter.GenRandomFilePath(ChartExtension);
            string bmValue   = MarkupUtilities.GenTextXslTag(chartName, XsltType.Select, true);
            string bmName    = BaseMarkupUtilities.XmlEncode(chartName);

            // create temporary image
            bmName = string.Format("{0}{1}{2}", MarkupConstant.MarkupPdeTag, bmName, MarkupConstant.MarkupPdeChart);
            ProntoDoc.Framework.Utils.FileHelper.FileFromBase64(chartContent, chartPath);

            // delete old bm
            Word.Bookmark oldBm = null;
            foreach (Word.Bookmark bookmark in wDoc.Bookmarks)
            {
                if (string.Equals(bmName, bookmark.Name, StringComparison.OrdinalIgnoreCase))
                {
                    oldBm = bookmark;
                    break;
                }
            }
            if (oldBm != null)
            {
                oldBm.Delete();
            }

            // add image into word
            wDoc.Application.Selection.TypeText(" ");
            Word.InlineShape inlineShape = wDoc.Application.Selection.InlineShapes.AddPicture(chartPath, false, true);
            inlineShape.AlternativeText = MarkupUtilities.CreateAlternativeText(bmName, bmValue);

            // add bookmark
            wDoc.Application.Selection.MoveLeft(Word.WdUnits.wdCharacter, 1);
            wDoc.Application.Selection.MoveRight(Word.WdUnits.wdCharacter, 1, Word.WdMovementType.wdExtend);
            wDoc.Bookmarks.Add(bmName, wDoc.Application.Selection.Range);
            wDoc.Application.Selection.MoveRight(Word.WdUnits.wdCharacter);

            // delete temporary file
            System.IO.File.Delete(chartPath);

            return(bmName);
        }
Exemple #29
0
        /// <summary>
        /// 将InlineShape转换为Image
        /// </summary>
        /// <param name="shape"></param>
        /// <returns></returns>
        private System.Drawing.Image ConvertToImage(Word.InlineShape shape)
        {
            if (shape == null)
            {
                return(null);
            }
            shape.Select();
            m_Doc.Application.Selection.Copy();
            //Globals.ThisAddIn.Application.Selection.Copy();

            if (System.Windows.Forms.Clipboard.GetDataObject() != null)
            {
                var data = System.Windows.Forms.Clipboard.GetDataObject();
                if (data != null && data.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap))
                {
                    System.Drawing.Image img = (System.Drawing.Image)data.GetData(System.Windows.Forms.DataFormats.Bitmap, true);
                    return(img);
                }
            }
            return(null);
        }
Exemple #30
0
        /// <summary>
        /// 导出excel中的chart对象到word中
        /// </summary>
        /// <param name="cht">excel中的chart对象</param>
        /// <param name="range">此时word文档中的全局range的位置或者范围</param>
        /// <remarks>由局部安全的原则,在进行绘图前,将另起一行,并将段落样式设置为“图片”样式</remarks>
        private void Export_ExcelChart(Chart cht, ref Word.Range range)
        {
            cht.Application.ScreenUpdating = false;
            try
            {
                // 下面复制Chart的操作中,如果监测曲线图所使用的Chart模板有问题,则可能会出错。
                Excel.ChartObject chtObj = cht.Parent as Excel.ChartObject;
                chtObj.Activate();
                chtObj.Copy(); // 或者用  cht.ChartArea.Copy()都可以。
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "导出监测曲线图\"" + cht.Application.Caption.ToString() + "\"出错(请检查是否是用户使用的Chart模板有问题),跳过此图的导出。" +
                    "\r\n" + ex.Message + "\r\n" + "报错位置:" +
                    ex.TargetSite.Name, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //刷新excel屏幕
                cht.Application.ScreenUpdating = true;
                return;
            }
            //设置word.range的格式
            Word.Range with_1 = range;
            //新起一行,并设置新段落的段落样式为图片
            NewLine(range, ParagraphStyle.picture);

            //进行粘贴,下面也可以用:DataType:=23
            with_1.PasteSpecial(DataType: Word.WdPasteDataType.wdPasteOLEObject, Placement: Word.WdOLEPlacement.wdInLine);


            Word.InlineShape shp = default(Word.InlineShape);
            range.Select();
            range.Application.Selection.MoveLeft(Unit: Word.WdUnits.wdCharacter, Count: 1,
                                                 Extend: Word.WdMovementType.wdExtend);
            shp = range.Application.Selection.InlineShapes[1];
            //约束图形的宽度,将其限制在word页面的正文宽度之内
            WidthRestrain(shp, ContentWidth);

            //刷新excel屏幕
            cht.Application.ScreenUpdating = true;
        }