static void MakeSmallImage(FileInfo sourceFileInfo, string newFileName, Word.Shape shape = null) { using (var img = Image.FromFile(sourceFileInfo.FullName)) { var expectedWidth = shape == null ? img.Width * .2 : new Word.Global().PointsToInches(shape.Width) * 400; var scale = expectedWidth / img.Width; var fi = new FileInfo(newFileName); if (fi.Exists) { var newImg = Image.FromFile(newFileName); var ratio = expectedWidth / newImg.Width; if (ratio > .95 && (ratio < 1.05 || scale > 0.95)) { return; } } if (scale > 0.95) { sourceFileInfo.CopyTo(newFileName, true); return; } using (var newImg = img.Scale(scale)) { if (fi.Exists) { fi.Delete(); } newImg.Save(newFileName, ImageFormat.Jpeg); } } }
public static void FloatImages(bool onlySelected = false) { try { switch (activeSelection.Type) { //Fall: Nur eine Inline Shape (also ein Bild) ausgewählt --> das ausgewählte Bild wird floaty case Word.WdSelectionType.wdSelectionInlineShape: activeSelection.ChildShapeRange.WrapFormat.Type = Word.WdWrapType.wdWrapThrough; break; //Fall: Auswahl mit keinen oder mehreren Bilder --> Alle ausgewählten Bilder werden floaty case Word.WdSelectionType.wdSelectionNormal: foreach (Word.InlineShape inlineShape in activeSelection.InlineShapes) { Word.Shape shape = inlineShape.ConvertToShape(); shape.WrapFormat.Type = Word.WdWrapType.wdWrapThrough; } break; //Fall: Keine Auswahl --> Alle Bilder im gesamten Dokument werden floaty case Word.WdSelectionType.wdSelectionIP: foreach (Word.InlineShape inlineShape in activeDocument.InlineShapes) { Word.Shape shape = inlineShape.ConvertToShape(); shape.WrapFormat.Type = Word.WdWrapType.wdWrapThrough; } break; } } catch (System.Runtime.InteropServices.COMException e) { MessageBox.Show(e.Message); } }
public ShapsOps(T shape, string typeName) { shapsOps = shape; Name = typeName; switch (typeName) { case "PowerPnt.Shape": pptShape = shape as PowerPnt.Shape; //shapsOps = pptShape; break; case "WinWord.Shape": docShape = shape as WinWord.Shape; //shapsOps = docShape; break; case "PowerPnt.ShapeRange": pptShapeRng = (PowerPnt.ShapeRange)shape; //shapsOps = pptShapeRng; break; case "WinWord.ShapeRange": docShapeRng = (WinWord.ShapeRange)shape; //shapsOps = docShapeRng; break; default: break; } }
private void button1_Click(object sender, RibbonControlEventArgs e) { _application.ScreenUpdating = false; Document doc = _application.Documents.OpenNoRepairDialog("D:/yoo/简历/吴雨希简历.docx"); _application.Selection.EndKey(WdUnits.wdStory, WdMovementType.wdMove); DocumentInfo docInfo = new DocumentInfo(); docInfo.Size.Width = doc.PageSetup.PageWidth; docInfo.Size.Height = doc.PageSetup.PageHeight; for (var i = 1; i <= doc.Paragraphs.Count; i++) { var obj = doc.Paragraphs[i].Range; TextRange textRange = GetTextRangInfo(obj); if (textRange != null && !string.IsNullOrEmpty(textRange.Text)) { docInfo.TextRanges.Add(textRange); } } for (int i = 1; i <= doc.Shapes.Count; i++) { Shape s = doc.Shapes[i]; var list = GetShapeTextRange(s); if (list.Any()) { docInfo.TextRanges.AddRange(list); } } doc.Close(WdSaveOptions.wdDoNotSaveChanges); _application.ScreenUpdating = true; File.WriteAllText(@"D:\yoo\out.json", JsonConvert.SerializeObject(docInfo), Encoding.UTF8); }
/// <summary> /// NOT YET FULLY IMPLEMENTED! /// </summary> /// <returns></returns> public WordController WriteBox() { W.Document doc = ActiveDocument; W.Shape shape = doc.Shapes.AddShape((int)MsoAutoShapeType.msoShapeRectangle, 0, 0, 10, 10); throw new NotImplementedException(); return(this); }
private List <TextRange> GetShapeTextRange(Shape s) { List <TextRange> list = new List <TextRange>(); if (s.Type == MsoShapeType.msoGroup) { foreach (Shape childShape in s.GroupItems) { list.AddRange(GetShapeTextRange(childShape)); } } else { if (s.TextFrame.HasText == MsoTrue) { for (var i = 1; i <= s.TextFrame.TextRange.Paragraphs.Count; i++) { var obj = s.TextFrame.TextRange.Paragraphs[i].Range; TextRange textRange = GetTextRangInfo(obj); if (textRange != null && !string.IsNullOrEmpty(textRange.Text)) { list.Add(textRange); } } } } return(list); }
/// <summary> /// Redact all shapes in a range. /// </summary> /// <param name="StoryRange">A range containing zero or more shapes.</param> private void RedactShapes(Word.Range StoryRange) { if (StoryRange.ShapeRange.Count > 0) { List <int> ShapeLocations = new List <int>(); Dictionary <int, Word.Shape> Shapes = new Dictionary <int, Word.Shape>(); //scan for shapes //since we're messing with the text, we need reorder them back to front by document order (they're in z-order). foreach (Word.Shape Shape in StoryRange.ShapeRange) { Word.Range AnchorRange = Shape.Anchor; ShapeLocations.Add(AnchorRange.Start); Shapes.Add(AnchorRange.Start, Shape); } //sort the anchor locations ShapeLocations.Sort(); for (int i = ShapeLocations.Count - 1; i >= 0; i--) { Word.Shape Shape = Shapes[ShapeLocations[i]]; if (RedactCommon.IsMarkedRange(Shape.Anchor, ShadingColor)) { Debug.WriteLine("Shape from " + Shape.Anchor.Start + " to " + Shape.Anchor.End + "to be redacted."); RedactShape(StoryRange.Document, Shape); } } } }
public void ProcShapes(WORD.Shape shape) { shape.TextFrame.TextRange.LanguageID = LocalLang.wdID; var sourceFont = !string.IsNullOrEmpty(shape.TextEffect.Text) ? shape.TextEffect.FontName : shape.TextFrame2.TextRange.Font.Name; var targetFont = LocalLang.GetLocFont(sourceFont); //_SetFontProperty(targetFont, shape.TextEffect.FontName, shape.TextFrame.TextRange.Font.Name, // shape.TextFrame.TextRange.Font.NameAscii, shape.TextFrame.TextRange.Font.NameOther); shape.TextEffect.FontName = targetFont; shape.TextFrame.TextRange.Font.NameAscii = targetFont; shape.TextFrame.TextRange.Font.NameOther = targetFont; if (LocalLang.IsFarEast) { shape.TextFrame.TextRange.LanguageIDFarEast = LocalLang.wdID; shape.TextFrame.TextRange.Font.NameFarEast = targetFont; } if (LocalLang.IsRightToLeft) { shape.TextFrame.TextRange.LanguageIDOther = LocalLang.wdID; shape.TextFrame.TextRange.Font.NameBi = targetFont; } }
private void ExtractShapeContents(List <string> contents, Word.Shape shape) { shape.Select();//shape.Type fails if not selected. This problem is word only. if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoGroup) { //To check group or not, use only shape.AutoShapeType == msoShapeMixed or shape.Type == msoGroup, //because other ways like shape.GroupItem.Count & shape.Ungroup thow an exception when shape is not a group. foreach (Word.Shape subShape in shape.GroupItems) { ExtractShapeContents(contents, subShape); } } else if (shape.Type == Microsoft.Office.Core.MsoShapeType.msoCanvas) { foreach (Word.Shape subShape in shape.CanvasItems) { ExtractShapeContents(contents, subShape); } } else { if (shape.TextFrame != null && shape.TextFrame.HasText != 0) { var text = shape.TextFrame?.TextRange?.Text; if (!String.IsNullOrEmpty(text)) { contents.Add(text); } } } }
/// <summary> /// Search and replace all occurences of a string in a active document. /// </summary> /// <param name="app">Word application instance.</param> /// <param name="find">String to search for.</param> /// <param name="replaceWith">String to replace the searched value with.</param> /// <param name="textColor">A color to give to the replaced text.</param> public void searchAndReplace(Document wordDocument, string find, string replaceWith, Color textColor = new Color(), bool searchInLastTextBox = false) { if (!searchInLastTextBox) { //Bug fix for searching and replacing it with long strings. Fix it by calling this function recursifly. string replaceWithPart = ""; if (replaceWith.Length > searchReplaceLenght) { replaceWithPart = replaceWith.Substring(searchReplaceLenght); replaceWith = replaceWith.Substring(0, searchReplaceLenght) + "<rep>"; } Microsoft.Office.Interop.Word.Find findObject = this.app.Selection.Find; findObject.ClearFormatting(); findObject.Text = find; findObject.Replacement.ClearFormatting(); findObject.Replacement.Text = replaceWith; //Set text color if it is given. if (textColor != new Color()) { findObject.Replacement.Font.Color = (Microsoft.Office.Interop.Word.WdColor)(textColor.R + 0x100 * textColor.G + 0x10000 * textColor.B); } object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); //Call searchAndReplace recursively if we have a long string. if (replaceWithPart.Length > 0) { searchAndReplace(wordDocument, "<rep>", replaceWithPart, textColor, searchInLastTextBox); } } else { //Also check shapes Microsoft.Office.Interop.Word.Shape shape = wordDocument.Shapes[wordDocument.Shapes.Count]; //Is it a textbox. if (shape.Type == MsoShapeType.msoTextBox) { Microsoft.Office.Interop.Word.Find findObject = shape.TextFrame.TextRange.Find; findObject.ClearFormatting(); findObject.Text = find; findObject.Replacement.ClearFormatting(); findObject.Replacement.Text = replaceWith; findObject.Execute((object)find, ref missing, ref missing, ref missing, ref missing, ref missing, ref paramFalse, ref missing, ref missing, (object)replaceWith, ref missing, ref missing, ref missing, ref missing, ref missing); } } }
/// <summary> /// Write an image to the end of the active document /// </summary> /// <param name="filePath"></param> public WordController WriteImage(FilePath filePath) { W.Document doc = ActiveDocument; Range range = EndRange(); InlineShape iShape = doc.InlineShapes.AddPicture(filePath.Path, false, true, range); W.Shape shape = iShape.ConvertToShape(); shape.Left = (float)WdShapePosition.wdShapeCenter; shape.WrapFormat.Type = WdWrapType.wdWrapInline; iShape.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; return(this); }
static IEnumerable <Word.Shape> AllShapes(this Word.Shape shape) { if (shape.Type == MsoShapeType.msoGroup) { foreach (var child in shape.GroupItems.Items().SelectMany(AllShapes)) { yield return(child); } } else { yield return(shape); } }
public void InsertImage(string strPicPath, float picWidth, float picHeight) { string FileName = strPicPath; object LinkToFile = false; object SaveWithDocument = true; object Anchor = word.Selection.Range; word.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor).Select(); word.Selection.InlineShapes[1].Width = picWidth; // 图片宽度 word.Selection.InlineShapes[1].Height = picHeight; // 图片高度 // 将图片设置为四面环绕型 Microsoft.Office.Interop.Word.Shape s = word.Selection.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; }
public static double GetYFromShape(Microsoft.Office.Interop.Word.Shape shp) { double y = shp.Top; Range shapeAnchor = shp.Anchor.Duplicate; object collapse = WdCollapseDirection.wdCollapseStart; shapeAnchor.Collapse(collapse); double anchorY = shapeAnchor.Information[WdInformation.wdVerticalPositionRelativeToPage]; if (y != anchorY) { y += anchorY; } return(y); }
public static double GetXFromShape(Microsoft.Office.Interop.Word.Shape shp) { double x = shp.Left; Range shapeAnchor = shp.Anchor.Duplicate; object collapse = WdCollapseDirection.wdCollapseStart; shapeAnchor.Collapse(collapse); double anchorX = shapeAnchor.Information[WdInformation.wdHorizontalPositionRelativeToPage]; if (x != anchorX) { x += anchorX; } return(x); }
/// <summary> /// 插入图片 /// </summary> /// <param name="imgPath"></param> /// <param name="width"></param> /// <param name="heigth"></param> /// <param name="wrapType">图文排版</param> public void AddImagin(string imgPath, float width, float heigth, WdWrapType wrapType) { object LinkToFile = false; object SaveWithDocument = true; object Anchor = document.Application.Selection.Range; document.Application.ActiveDocument.InlineShapes.AddPicture(imgPath, ref LinkToFile, ref SaveWithDocument, ref Anchor); //document.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度 //document.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度 document.Application.ActiveDocument.InlineShapes[1].Width = 100f; //图片宽度 document.Application.ActiveDocument.InlineShapes[1].Height = 100f; //图片高度 //将图片设置为四周环绕型 Word.Shape s = document.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); s.WrapFormat.Type = wrapType;//Word.WdWrapType.wdWrapSquare; }
public void StartSpellChecking() { Cursor.Current = Cursors.WaitCursor; Globals.ThisAddIn.SpellOn = true; ResetAllInitVariables(); if (!tabControl.TabPages.Contains(tabPage1)) { tabControl.TabPages.Add(tabPage1); } tabControl.SelectTab(tabPage1); m_Inspector = Globals.ThisAddIn.Application.ActiveInspector(); m_Document = m_Inspector.WordEditor; if (!m_Inspector.IsWordMail()) { m_Document = m_Inspector.CurrentItem as Word.Document; } // get the cursor position in the document nCursorPos = m_Document.Application.Selection.Start; // get all shapes in the document oShapes = m_Document.Application.ActiveDocument.Shapes; Word.ShapeRange oShpRng = m_Document.Application.Selection.ShapeRange; if (oShpRng.Count > 0) { object obj = 1; Word.Shape shp = oShpRng.get_Item(ref obj); bCheckNormalText = false; bCursorInShape = true; for (int i = 1; i <= oShapes.Count; i++) { obj = i; nShapeIndex = i; Word.Shape oShp = oShapes.get_Item(ref obj); if (oShp.Name == shp.Name) { break; } } } RestartParagraph(); SetSpellingState("Անտեսել"); }
/// <summary> /// Redact a shapes by replacing it with a 1px image. /// </summary> /// <param name="Document">The document containing the shape.</param> /// <param name="ShapeToRedact">The shape to redact.</param> private void RedactShape(Word.Document Document, Word.Shape ShapeToRedact) { string ImagePath = RedactCommon.CreateRedactedImage(); object AnchorRange = ShapeToRedact.Anchor; object Height = ShapeToRedact.Height; object Width = ShapeToRedact.Width; object Top = ShapeToRedact.Top; object Left = ShapeToRedact.Left; object WrapType = ShapeToRedact.WrapFormat.Type; ((Word.Range)AnchorRange).Select(); ShapeToRedact.Delete(); Word.Shape RedactedImage = Document.Shapes.AddPicture(ImagePath, ref Missing, ref Missing, ref Left, ref Top, ref Width, ref Height, ref AnchorRange); RedactedImage.AlternativeText = string.Empty; RedactedImage.WrapFormat.Type = (Word.WdWrapType)WrapType; }
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(); }
public void GetFromDocumentShape(Document doc, ContentControl cc, Microsoft.Office.Interop.Word.Shape shp) { DateTime timerStart = DateTime.Now; FieldType = WordFieldInfo.ConvertFieldType(cc); if (FieldType == FieldType.DropDownList) { Options = GetOptions(cc); } X = GetXFromShape(shp); Y = GetYFromShape(shp); Height = shp.Height; Width = shp.Width; Page = cc.Range.Information[WdInformation.wdActiveEndPageNumber]; Status = "Done"; DateTime timerStop = DateTime.Now; TimeToGetLocation = timerStop - timerStart; }
/// <summary> /// Inserts a watermark into a document. /// </summary> /// <param name="doc">The input document.</param> /// <param name="watermarkText">Text of the watermark.</param> public void insertWatermarkText(Document doc, string watermarkText) { Microsoft.Office.Interop.Word.Shape nShape = null; foreach (Section section in doc.Sections) { nShape = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, watermarkText, "Gotham Light", 100, MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 0); nShape.Fill.Visible = MsoTriState.msoTrue; nShape.Line.Visible = MsoTriState.msoFalse; nShape.Rotation = 45; nShape.Fill.Solid(); nShape.Fill.ForeColor.RGB = (Int32)WdColor.wdColorGray20; nShape.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin; nShape.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; // center location nShape.Left = (float)WdShapePosition.wdShapeCenter; nShape.Top = (float)WdShapePosition.wdShapeCenter; } }
private bool HasText(Word.Shape oShape) { bool bHasText = false; try { Word.TextFrame txtFrame = oShape.TextFrame; if (txtFrame.HasText != 0) { bHasText = true; } } catch (Exception e) { bHasText = false; } return(bHasText); }
public static void SaveShapeToFile(Word.Shape shape) { if (shape == null) { return; } shape.Select(); 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); img.Save(@"d:\TT.jpg"); } } }
public void InsertLine(float left, float top, float width, float weight, int r, int g, int b) { //SetFontColor("red"); //SetAlignment("Center"); object Anchor = word.Selection.Range; //int pLeft = 0, pTop = 0, pWidth = 0, pHeight = 0; //word.ActiveWindow.GetPoint(out pLeft, out pTop, out pWidth, out pHeight,objMissing); //MessageBox.Show(pLeft + "," + pTop + "," + pWidth + "," + pHeight); object rep = false; //left += word.ActiveDocument.PageSetup.LeftMargin; left = word.CentimetersToPoints(left); top = word.CentimetersToPoints(top); width = word.CentimetersToPoints(width); Microsoft.Office.Interop.Word.Shape s = word.ActiveDocument.Shapes.AddLine(0, top, width, top, ref Anchor); s.Line.ForeColor.RGB = RGB(r, g, b); s.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue; s.Line.Style = Microsoft.Office.Core.MsoLineStyle.msoLineSingle; s.Line.Weight = weight; }
//private static void AddHeader1(Application WordApp, string HeaderText, WdParagraphAlignment wdAlign) //{ // Object oMissing = System.Reflection.Missing.Value; // WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; // WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; // Microsoft.Office.Interop.Word.Shape textBox = WordApp.ActiveDocument.Shapes.AddTextbox(MsoTextOrientation.msoTextOrientationVertical, 150, 10, 40, 40); // textBox.TextFrame.TextRange.Text = HeaderText; // WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; //} private static void AddFooterWord(Application WordApp, string fileId, WdParagraphAlignment wdAlign, Document document) { // TODO: add footer to every page. look into using document.sections() something float pageHeight = (float)document.ActiveWindow.Selection.PageSetup.PageHeight; Object oMissing = System.Reflection.Missing.Value; WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter; Microsoft.Office.Interop.Word.Shape tagLineLabel = WordApp.ActiveDocument.Shapes.AddLabel(MsoTextOrientation.msoTextOrientationHorizontal, 100, pageHeight - 25, 150, 25); tagLineLabel.TextFrame.TextRange.Text = "Printed with \u2764 by Preasy"; tagLineLabel.Line.Visible = MsoTriState.msoFalse; Microsoft.Office.Interop.Word.Shape fileIdLabel = WordApp.ActiveDocument.Shapes.AddLabel(MsoTextOrientation.msoTextOrientationHorizontal, 20, pageHeight - 25, 75, 25); fileIdLabel.TextFrame.TextRange.Text = fileId; fileIdLabel.Line.Visible = MsoTriState.msoFalse; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; }
/// <summary> /// Inserts a watermark image into a document. /// </summary> /// <param name="doc">The input document.</param> /// <param name="watermarkText">Text of the watermark.</param> public void insertWatermarkImage(Document doc, int pageNumber, byte[] image) { String tempTemplateFile = Path.GetTempPath() + "/temp.png"; File.WriteAllBytes(tempTemplateFile, image); Microsoft.Office.Interop.Word.Shape nShape = null; Section section = doc.Sections[pageNumber]; nShape = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddPicture(tempTemplateFile); nShape.Fill.Visible = MsoTriState.msoTrue; nShape.Line.Visible = MsoTriState.msoFalse; nShape.Rotation = 45; nShape.Fill.Solid(); nShape.Fill.ForeColor.RGB = (Int32)WdColor.wdColorGray20; nShape.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin; nShape.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin; // center location nShape.Left = (float)WdShapePosition.wdShapeCenter; nShape.Top = (float)WdShapePosition.wdShapeCenter; }
/// <summary> /// 将Shape对象转换为Image /// </summary> /// <param name="shape"></param> /// <returns></returns> private System.Drawing.Image ConvertToImage(Word.Shape 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); }
public static void CreateWatermark(string watermarkText, string path, string Signature, Application app) { try { var doc = app.Documents.Open(path); var shape = doc.Bookmarks["PicHere"].Range.InlineShapes.AddPicture(Signature, false, true); shape.Width = 345; shape.Height = 150; doc.Close(); object Missing = System.Reflection.Missing.Value; object oMissing = System.Reflection.Missing.Value; object saveChanges = null; Microsoft.Office.Interop.Word.Shape nShape = null; string wmText = watermarkText; foreach (Microsoft.Office.Interop.Word.Section section in doc.Sections) { nShape = section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Shapes.AddTextEffect(MsoPresetTextEffect.msoTextEffect1, wmText, "Calibri", (float)80, MsoTriState.msoTrue, MsoTriState.msoFalse, 0, 350, ref oMissing); nShape.Fill.Visible = MsoTriState.msoTrue; nShape.Line.Visible = MsoTriState.msoFalse; nShape.Fill.Solid(); nShape.Fill.ForeColor.RGB = (Int32)WdColor.wdColorGray80; nShape.Left = (float)WdShapePosition.wdShapeLeft; nShape.Top = 250; nShape.Rotation = -45; } object newFile = path; object a = 11; doc.SaveAs(ref newFile, ref a, 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); doc.Close(ref saveChanges, ref oMissing, ref oMissing); app.Quit(ref saveChanges, ref Missing, ref Missing); } catch { } }
//<Snippet15> private void ChartOptions1_SelectionChanged(object sender, EventArgs e) { try { object index = 1; Word.Shape shape = this.Shapes.get_Item(ref index); // Activate the shape. shape.OLEFormat.Activate(); Microsoft.Office.Interop.Graph.Chart dataChart = (Microsoft.Office.Interop.Graph.Chart)shape.OLEFormat.Object; dataChart.ChartType = this.ChartOptions1.Selection; // Deactivate the shape. this.ChartOptions1.Select(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public void InsertShape(Word.Document doc) { try { Word.Section sec = doc.Sections[1]; Word.HeaderFooter foo = sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]; Word.Range rng = foo.Range; float leftPos = doc.PageSetup.PageWidth - doc.PageSetup.RightMargin; float topPos = doc.PageSetup.PageHeight - doc.PageSetup.BottomMargin; Word.Shape shp = doc.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal, leftPos, topPos, 50, 20, rng); shp.TextFrame.TextRange.Text = "Text"; shp.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionBottomMarginArea; } catch (Exception) { throw; } }
private int check_Kernel(List<OfficeElement> ls) { int points = 0, i; int curPart = -1; //当前正在分析哪一部分的考点 for (i = 0; i < ls.Count; i++) { OfficeElement oe = ls[i]; #region 具体考点对象定位 if (oe.AttribName == "Root") continue; if (oe.AttribName == "Documents") continue; if (oe.AttribName == "Paragraph") { #region 段落定位 try { int paraIdx = int.Parse(oe.AttribValue); stuPara = stuDoc.Paragraphs[paraIdx]; ansPara = ansDoc.Paragraphs[paraIdx]; } catch { points = 0; break; } #endregion curPart = PART_PARAGRAPH; continue; } if (oe.AttribName == "Table") { #region 表格定位 try { int tabIdx = int.Parse(oe.AttribValue); stuTab = stuDoc.Tables[tabIdx]; ansTab = ansDoc.Tables[tabIdx]; } catch { points = 0; break; } #endregion curPart = PART_TABLE; continue; } if (oe.AttribName == "Cell") { #region 单元格定位 try { int rowIdx, colIdx, commaIdx; commaIdx = oe.AttribValue.IndexOf(','); rowIdx = int.Parse(oe.AttribValue.Substring(0, commaIdx)); colIdx = int.Parse(oe.AttribValue.Substring(commaIdx + 1)); stuCell = stuTab.Cell(rowIdx, colIdx); ansCell = ansTab.Cell(rowIdx, colIdx); } catch { points = 0; break; } #endregion curPart = PART_CELL; continue; } if (oe.AttribName == "Textbox") { #region 文本框定位 try { int tbIdx = int.Parse(oe.AttribValue); object ob = tbIdx; stuSp = stuDoc.Shapes.get_Item(ref ob); ansSp = ansDoc.Shapes.get_Item(ref ob); stuTf = stuSp.TextFrame; ansTf = ansSp.TextFrame; } catch { points = 0; break; } #endregion curPart = PART_TEXTBOX; continue; } if (oe.AttribName == "PageSetup") { #region 页面设置定位 try { stuPs = stuDoc.PageSetup; ansPs = ansDoc.PageSetup; } catch { points = 0; break; } #endregion continue; } #endregion #region 段落属性判分 if (curPart == PART_PARAGRAPH) { switch (oe.AttribName) { case "Indent": break; case "Font": stuRange = stuPara.Range; ansRange = ansPara.Range; break; case "Dropcap": stuDc = stuPara.DropCap; ansDc = ansPara.DropCap; break; case "TextColumns": stuTc = stuPara.Range.PageSetup.TextColumns; ansTc = ansPara.Range.PageSetup.TextColumns; break; #region 段落部分 case "Alignment": if (stuPara.Alignment == ansPara.Alignment) points = int.Parse(oe.AttribValue); break; case "CharacterUnitFirstLineIndent": if (stuPara.CharacterUnitFirstLineIndent == ansPara.CharacterUnitFirstLineIndent) points = int.Parse(oe.AttribValue); break; case "CharacterUnitLeftIndent": if (stuPara.CharacterUnitLeftIndent == ansPara.CharacterUnitLeftIndent) points = int.Parse(oe.AttribValue); break; case "CharacterUnitRightIndent": if (stuPara.CharacterUnitRightIndent == ansPara.CharacterUnitRightIndent) points = int.Parse(oe.AttribValue); break; case "LineUnitBefore": if (stuPara.LineUnitBefore == ansPara.LineUnitBefore) points = int.Parse(oe.AttribValue); break; case "LineUnitAfter": if (stuPara.LineUnitAfter == ansPara.LineUnitAfter) points = int.Parse(oe.AttribValue); break; case "LineSpacingRule": if (stuPara.LineSpacingRule == ansPara.LineSpacingRule) points = int.Parse(oe.AttribValue); break; case "LineSpacing": if (stuPara.LineSpacing == ansPara.LineSpacing) points = int.Parse(oe.AttribValue); break; #endregion #region 文字部分 case "Text": if (stuRange.Text == ansRange.Text) points = int.Parse(oe.AttribValue); break; case "FontSize": if (stuRange.Font.Size == ansRange.Font.Size) points = int.Parse(oe.AttribValue); break; case "FontName": if (stuRange.Font.Name == ansRange.Font.Name) points = int.Parse(oe.AttribValue); break; case "Bold": if (stuRange.Font.Bold == ansRange.Font.Bold) points = int.Parse(oe.AttribValue); break; case "Italic": if (stuRange.Font.Italic == ansRange.Font.Italic) points = int.Parse(oe.AttribValue); break; case "Underline": if (stuRange.Font.Underline == ansRange.Font.Underline) points = int.Parse(oe.AttribValue); break; case "UnderlineColor": if (stuRange.Font.UnderlineColor == ansRange.Font.UnderlineColor) points = int.Parse(oe.AttribValue); break; case "ForeColor": if (stuRange.Font.Color == ansRange.Font.Color) points = int.Parse(oe.AttribValue); break; case "HighLightColor": if (stuRange.HighlightColorIndex == ansRange.HighlightColorIndex) points = int.Parse(oe.AttribValue); break; case "Superscript": if (stuRange.Font.Superscript == ansRange.Font.Superscript) points = int.Parse(oe.AttribValue); break; case "Subscript": if (stuRange.Font.Subscript == ansRange.Font.Subscript) points = int.Parse(oe.AttribValue); break; case "Spacing": if (stuRange.Font.Spacing == ansRange.Font.Spacing) points = int.Parse(oe.AttribValue); break; case "Animation": if (stuRange.Font.Animation == ansRange.Font.Animation) points = int.Parse(oe.AttribValue); break; case "BackgroundPatternColor": if (stuRange.Shading.BackgroundPatternColor == ansRange.Shading.BackgroundPatternColor) points = int.Parse(oe.AttribValue); break; #endregion #region 首字下沉 case "Position": if (stuDc.Position == ansDc.Position) points = int.Parse(oe.AttribValue); break; case "DcFontName": if (stuDc.FontName == ansDc.FontName) points = int.Parse(oe.AttribValue); break; case "LinesToDrop": if (stuDc.LinesToDrop == ansDc.LinesToDrop) points = int.Parse(oe.AttribValue); break; case "DistanceFromText": if (stuDc.DistanceFromText == ansDc.DistanceFromText) points = int.Parse(oe.AttribValue); break; #endregion #region 分栏与栏宽 case "TextColumnsCount": if (stuTc.Count == ansTc.Count) points = int.Parse(oe.AttribValue); break; case "TextColumnsWidth": if (stuTc.Width == ansTc.Width) points = int.Parse(oe.AttribValue); break; case "TextColumnsSpacing": if (stuTc.Spacing == ansTc.Spacing) points = int.Parse(oe.AttribValue); break; case "TextColumnsLineBetween": if (stuTc.LineBetween == ansTc.LineBetween) points = int.Parse(oe.AttribValue); break; #endregion } continue; } #endregion #region 表格属性判分 if (curPart == PART_TABLE) { switch (oe.AttribName) { case "Rows": if (stuTab.Rows.Count == ansTab.Rows.Count) points = int.Parse(oe.AttribValue); break; case "Columns": if (stuTab.Columns.Count == ansTab.Columns.Count) points = int.Parse(oe.AttribValue); break; } continue; } #endregion #region 单元格属性判分 if (curPart == PART_CELL) { switch (oe.AttribName) { case "Text": if (stuCell.Range.Text == ansCell.Range.Text) points = int.Parse(oe.AttribValue); break; case "Height": if (stuCell.Height == ansCell.Height) points = int.Parse(oe.AttribValue); break; case "Width": if (stuCell.Width == ansCell.Width) points = int.Parse(oe.AttribValue); break; } continue; } #endregion #region 文本框属性判分 if (curPart == PART_TEXTBOX) { switch (oe.AttribName) { case "Text": if (stuTf.TextRange.Text == ansTf.TextRange.Text) points = int.Parse(oe.AttribValue); break; case "Orientation": if (stuTf.Orientation == ansTf.Orientation) points = int.Parse(oe.AttribValue); break; case "FontName": if (stuTf.TextRange.Font.Name == ansTf.TextRange.Font.Name) points = int.Parse(oe.AttribValue); break; case "FontSize": if (stuTf.TextRange.Font.Size == ansTf.TextRange.Font.Size) points = int.Parse(oe.AttribValue); break; case "ForeColor": if (stuTf.TextRange.Font.Color == ansTf.TextRange.Font.Color) points = int.Parse(oe.AttribValue); break; case "HighLightColor": if (stuTf.TextRange.HighlightColorIndex == ansTf.TextRange.HighlightColorIndex) points = int.Parse(oe.AttribValue); break; case "Spacing": if (stuTf.TextRange.Font.Spacing == ansTf.TextRange.Font.Spacing) points = int.Parse(oe.AttribValue); break; case "Alignment": if (stuTf.TextRange.ParagraphFormat.Alignment == ansTf.TextRange.ParagraphFormat.Alignment) points = int.Parse(oe.AttribValue); break; } continue; } #endregion #region 页面设置属性判分 if (curPart == PART_PAGESETUP) { switch (oe.AttribName) { case "TopMargin": if (stuPs.TopMargin == ansPs.TopMargin) points = int.Parse(oe.AttribValue); break; case "BottomMargin": if (stuPs.BottomMargin == ansPs.BottomMargin) points = int.Parse(oe.AttribValue); break; case "LeftMargin": if (stuPs.LeftMargin == ansPs.LeftMargin) points = int.Parse(oe.AttribValue); break; case "RightMargin": if (stuPs.RightMargin == ansPs.RightMargin) points = int.Parse(oe.AttribValue); break; case "HeaderDistance": if (stuPs.HeaderDistance == ansPs.HeaderDistance) points = int.Parse(oe.AttribValue); break; case "FooterDistance": if (stuPs.FooterDistance == ansPs.FooterDistance) points = int.Parse(oe.AttribValue); break; case "Orientation": if (stuPs.Orientation == ansPs.Orientation) points = int.Parse(oe.AttribValue); break; case "GutterPos": if (stuPs.GutterPos == ansPs.GutterPos) points = int.Parse(oe.AttribValue); break; } continue; } #endregion } return points; }