关于目录标签的一些解析可以看下这篇文章:https://www.cnblogs.com/xuanhun/archive/2011/06/16/2083061.html
以下是我自己的学习记录。
首先打开文档,获取body
using (WordprocessingDocument doc = WordprocessingDocument.Open(file, true)) { MainDocumentPart docPart = doc.MainDocumentPart; Body body = docPart.Document.Body; }
通过body获取1-5级目录标签
var parHasStyle = body.Descendants<Paragraph>().Where(t => t.Descendants<ParagraphStyleId>().Count() > 0 && t.Descendants<ParagraphStyleId>().All(c => c.Val == "1" || c.Val == "2" || c.Val == "3" || c.Val == "4" || c.Val == "5"));
下面是完整的获取标签,包含目录层级关系,目录的页码
/// <summary> /// 获取目录信息及页码 /// </summary> /// <returns></returns> public List<XmlMark> GetMenus() { List<XmlMark> menus = new List<XmlMark>(); Body body = _doc.MainDocumentPart.Document.Body; var pars = body.Descendants<SdtBlock>().First().Descendants<SdtContentBlock>().First().Descendants<Paragraph>(); foreach (var par in pars) { var txt = ToText(par); if (txt == "目录" || string.IsNullOrEmpty(txt)) continue; XmlMark xml = null; var hyperlink = par.Descendants<Hyperlink>().First(); if (hyperlink != null) { xml = new XmlMark(txt, hyperlink.Anchor); } else { var p = par.Descendants<FieldCode>().First(fc => fc.Text.Contains("HYPERLINK")); if (p == null) continue; var match = System.Text.RegularExpressions.Regex.Match(p.Text, "_Toc\d+"); if (!match.Success) continue; xml = new XmlMark(txt, match.Value); } var num = System.Text.RegularExpressions.Regex.Match(txt, "(?<=-\s)\d+(?=\s-)");//获取目录上的页码,格式:- 22 - if (!num.Success) continue; xml.PageIndex = Convert.ToInt32(num.Value); menus.Add(xml); } return menus; } /// <summary> /// 转成文本 /// </summary> /// <param name="p"></param> /// <returns></returns> private string ToText(Paragraph p) { return string.Join("", p.Descendants<Text>().Select(t => t.Text)); } /// <summary> /// 获取书签信息包含页码,标签的层级关系 /// </summary> /// <returns></returns> public List<XmlMark> GetMarks() { //用来匹配页码 var menus = GetMenus(); Dictionary<string, int> mark2pageindex = new Dictionary<string, int>(); foreach (var xml in menus) { mark2pageindex.Add(xml.BookmarkName, xml.PageIndex); } List<XmlMark> marks = new List<XmlMark>(); Body body = _doc.MainDocumentPart.Document.Body; var pars = body.Descendants<Paragraph>().Where(t => t.Descendants<ParagraphStyleId>().Count() > 0 && t.Descendants<ParagraphStyleId>().All(c => c.Val == "1" || c.Val == "2" || c.Val == "3" || c.Val == "4" || c.Val == "5")); XmlMark premark = null; foreach (var par in pars) { var mark = new XmlMark(par); if (string.IsNullOrEmpty(mark.BookmarkId)) continue; if (mark2pageindex.ContainsKey(mark.BookmarkName)) mark.PageIndex = mark2pageindex[mark.BookmarkName]; var parent = GetParentmark(premark, mark); if (parent == null) marks.Add(mark); else parent.AddItem(mark); premark = mark; } return marks; } /// <summary> /// 获取父标签 /// </summary> /// <param name="parent"></param> /// <param name="mark"></param> /// <returns></returns> private XmlMark GetParentmark(XmlMark parent, XmlMark mark) { if (parent == null) return null; if (mark.PStyleId == parent.PStyleId) return parent.Parent; if (mark.PStyleId.CompareTo(parent.PStyleId) > 0) return parent; else return GetParentmark(parent.Parent, mark); }
//标签数据类
public class XmlMark { public XmlMark(string name, string markName) { Name = name; BookmarkName = markName; } public XmlMark(Paragraph par) { Par = par; Name = par.InnerText; PStyleId = par.Descendants<ParagraphStyleId>().First().Val; var starts = par.Descendants<BookmarkStart>(); if (starts.Count() > 0) { BookmarkName = starts.First().Name; BookmarkId = starts.First().Id; } } public Paragraph Par { get; set; } public string Name { get; set; } public int PageIndex { get; set; } public string PStyleId { get; set; } public string BookmarkName { get; set; } public string BookmarkId { get; set; } public XmlMark Parent { get; set; } public List<XmlMark> MenuItems { get; private set; } = new List<XmlMark>(); public void AddItem(XmlMark menu) { menu.Parent = this; this.MenuItems.Add(menu); } public void RemoveItem(XmlMark menu) { this.MenuItems.Remove(menu); menu.Parent = null; } public void Clear() { MenuItems.ForEach(m => m.Parent = null); MenuItems.Clear(); } }
接下去就是添加数据:
首先是插入文本(使用只需要body.Append()就可以了)
/// <summary> /// 添加文本 /// </summary> /// <param name="txt">字符串</param> /// <param name="fontname">字体</param> /// <param name="fontSize">大小</param> /// <param name="isbold">是否加粗</param> /// <param name="horizontalcenter">水平居中</param> /// <param name="fontcolor">字体颜色</param> /// <returns></returns> public Paragraph AddText(string txt, string fontname = "宋体", int fontSize = 11, bool isbold = false, bool horizontalcenter = false, System.Drawing.Color fontcolor = default(System.Drawing.Color)) { Paragraph paragraph1 = new Paragraph(); ParagraphProperties paragraphProperties1 = new ParagraphProperties(); Justification justification1 = new Justification() { Val = JustificationValues.Center }; ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties(); RunFonts runFonts1 = new RunFonts() { Hint = FontTypeHintValues.EastAsia, Ascii = fontname, HighAnsi = fontname, EastAsia = fontname, ComplexScript = fontname }; FontSize fontSize1 = new FontSize() { Val = (fontSize * 2).ToString() }; FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = (fontSize * 2).ToString() }; Languages languages1 = new Languages() { Val = "en-US", EastAsia = "zh-CN" }; paragraphMarkRunProperties1.Append(runFonts1); if (isbold) paragraphMarkRunProperties1.Append(new Bold()); paragraphMarkRunProperties1.Append(fontSize1); paragraphMarkRunProperties1.Append(fontSizeComplexScript1); paragraphMarkRunProperties1.Append(languages1); if (horizontalcenter) paragraphProperties1.Append(justification1); paragraphProperties1.Append(paragraphMarkRunProperties1); Run run1 = new Run(); RunProperties runProperties1 = new RunProperties(); RunFonts runFonts2 = new RunFonts() { Hint = FontTypeHintValues.EastAsia, Ascii = fontname, HighAnsi = fontname, EastAsia = fontname, ComplexScript = fontname }; FontSize fontSize2 = new FontSize() { Val = (fontSize * 2).ToString() }; FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = (fontSize * 2).ToString() }; Languages languages2 = new Languages() { Val = "en-US", EastAsia = "zh-CN" }; runProperties1.Append(runFonts2); if (isbold) runProperties1.Append(new Bold()); if (fontcolor != default(System.Drawing.Color)) { var r = fontcolor.R.ToString("X"); var g = fontcolor.G.ToString("X"); var b = fontcolor.B.ToString("X"); string str = ""; if (r.Length == 1) str += "0"; str += r; if (g.Length == 1) str += "0"; str += g; if (b.Length == 1) str += "0"; str += b; runProperties1.Append(new Color() { Val = str }); } runProperties1.Append(fontSize2); runProperties1.Append(fontSizeComplexScript2); runProperties1.Append(languages2); Text text1 = new Text(); text1.Text = txt; run1.Append(runProperties1); run1.Append(text1); BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" }; BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" }; paragraph1.Append(paragraphProperties1); paragraph1.Append(run1); paragraph1.Append(bookmarkStart1); paragraph1.Append(bookmarkEnd1); return paragraph1; }
然后插入表格的代码:(使用只需要body.Append()就可以了)
public Table AddTable(System.Data.DataTable data) { var table = new Table(); var totalwidth = data.Columns.Count * 120 * 15; var tableProperties1 = new TableProperties(); var tableStyle1 = new TableStyle() { Val = "a7" }; var tableWidth1 = new TableWidth() { Width = totalwidth.ToString(), Type = TableWidthUnitValues.Dxa }; var tableJustification1 = new TableJustification() { Val = TableRowAlignmentValues.Center }; var tableLayout1 = new TableLayout() { Type = TableLayoutValues.Fixed }; var tableLook1 = new TableLook() { Val = "04A0", FirstRow = true, LastRow = false, FirstColumn = true, LastColumn = false, NoHorizontalBand = false, NoVerticalBand = true }; tableProperties1.Append(tableStyle1); tableProperties1.Append(tableWidth1); tableProperties1.Append(tableJustification1); tableProperties1.Append(tableLayout1); tableProperties1.Append(tableLook1); var tableGrid1 = new TableGrid(); int count = data.Columns.Count; for (int i = 0; i < count; ++i) { var gridColumn1 = new GridColumn() { Width = (120 * 15).ToString() }; } table.Append(tableProperties1); table.Append(tableGrid1); foreach (System.Data.DataRow row in data.Rows) { var tableRow1 = new TableRow(); var tableRowProperties1 = new TableRowProperties(); var tableRowHeight1 = new TableRowHeight() { Val = 400U, HeightType = HeightRuleValues.AtLeast }; var tableJustification2 = new TableJustification() { Val = TableRowAlignmentValues.Center }; tableRowProperties1.Append(tableRowHeight1); tableRowProperties1.Append(tableJustification2); var tablePropertyExceptions1 = new TablePropertyExceptions(); var tableBorders2 = new TableBorders(); var topBorder2 = new TopBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; var leftBorder2 = new LeftBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; var bottomBorder2 = new BottomBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; var rightBorder2 = new RightBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; var insideHorizontalBorder2 = new InsideHorizontalBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; var insideVerticalBorder2 = new InsideVerticalBorder() { Val = BorderValues.Single, Color = "auto", Size = 4U, Space = 0U }; tableBorders2.Append(topBorder2); tableBorders2.Append(leftBorder2); tableBorders2.Append(bottomBorder2); tableBorders2.Append(rightBorder2); tableBorders2.Append(insideHorizontalBorder2); tableBorders2.Append(insideVerticalBorder2); tablePropertyExceptions1.Append(tableBorders2); tableRow1.Append(tablePropertyExceptions1); tableRow1.Append(tableRowProperties1); for (int cellindex = 0; cellindex < data.Columns.Count; ++cellindex) { var cell = row[cellindex]; if (cell == null) { continue; } var tableCell1 = new TableCell(); var tableCellProperties1 = new TableCellProperties(); var tableCellWidth1 = new TableCellWidth() { Width = (120 * 15).ToString(), Type = TableWidthUnitValues.Dxa }; var tableCellVerticalAlignment1 = new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }; tableCellProperties1.Append(tableCellWidth1); tableCellProperties1.Append(tableCellVerticalAlignment1); var paragraph1 = new Paragraph(); var paragraphProperties1 = new ParagraphProperties(); var paragraphMarkRunProperties1 = new ParagraphMarkRunProperties(); var runFonts1 = new RunFonts() { Hint = FontTypeHintValues.Default, EastAsiaTheme = ThemeFontValues.MinorEastAsia }; var verticalTextAlignment1 = new VerticalTextAlignment() { Val = VerticalPositionValues.Baseline }; var languages1 = new Languages() { Val = "en-US", EastAsia = "zh-CN" }; var justification1 = new Justification() { Val = JustificationValues.Center }; paragraphMarkRunProperties1.Append(runFonts1); paragraphMarkRunProperties1.Append(verticalTextAlignment1); paragraphMarkRunProperties1.Append(languages1); paragraphProperties1.Append(paragraphMarkRunProperties1); paragraphProperties1.Append(justification1); paragraph1.Append(paragraphProperties1); var run1 = new Run(); var runProperties1 = new RunProperties(); var runFonts2 = new RunFonts() { Hint = FontTypeHintValues.EastAsia }; var verticalTextAlignment2 = new VerticalTextAlignment() { Val = VerticalPositionValues.Baseline }; var languages2 = new Languages() { Val = "en-US", EastAsia = "zh-CN" }; runProperties1.Append(runFonts2); runProperties1.Append(verticalTextAlignment2); runProperties1.Append(languages2); var text1 = new Text(); text1.Text = cell.ToString(); run1.Append(runProperties1); run1.Append(text1); paragraph1.Append(run1); tableCell1.Append(tableCellProperties1); tableCell1.Append(paragraph1); tableRow1.Append(tableCell1); } table.Append(tableRow1); } return table; }
接下去添加图片 可以看看这两篇文章https://www.jb51.net/article/55567.htm 和 https://blog.csdn.net/renfufei/article/details/77481753/
首先图片宽高对应关系:300*300对应的图片大小为:7.935cm*7.035cm,至于如何计算可以参考下面的计算换算规则:
然而Open xml中的度量单位为EMU(全称为 English Metric Unit),1cm =360000EMUS,所以7.935cm=7.935*360000=2857500
下面添加图片的代码:(使用只需要body.Append()就可以了)
/// <summary> /// 添加图片 /// </summary> /// <param name="picturePath">图片路径</param> /// <param name="width">宽度像素</param> /// <param name="height">高度像素</param> /// <param name="wrapType">图片环绕类型0=嵌入,1=四周环绕,2=紧密型环绕,3=穿越型环绕,4=上下型环绕,5=衬于文字下方,6=浮于文字上方</param> /// <param name="horizontalcenter">水平居中,仅对wrapType=0生效</param> /// <returns></returns> public Paragraph AddPicture(string picturePath, int width, int height, int wrapType = 0, bool horizontalcenter = false) { string picType = picturePath.Split('.').Last(); ImagePartType imagePartType; ImagePart imagePart = null; if (picType.ToLower() == "jpg") imagePartType = ImagePartType.Jpeg; else Enum.TryParse<ImagePartType>(picType, true, out imagePartType); imagePart = _doc.MainDocumentPart.AddImagePart(imagePartType); imagePart.FeedData(File.Open(picturePath, FileMode.Open)); // 读取图片二进制流 var piccount = _doc.MainDocumentPart.Document.Body.Descendants<Drawing>().Count(); return CreateImageParagraph(_doc.MainDocumentPart.GetIdOfPart(imagePart), Path.GetFileNameWithoutExtension(picturePath), ++piccount, width, height, wrapType, horizontalcenter); } /// <summary> /// 创建图片段落 /// </summary> /// <param name="relationshipId">图片引用id</param> /// <param name="picname">图片名</param> /// <param name="picindex">图片在doc中的索引,即第几张图</param> /// <param name="width">宽度像素</param> /// <param name="height">高度像素</param> /// <param name="wrapType">图片环绕类型0=嵌入,1=四周环绕,2=紧密型环绕,3=穿越型环绕,4=上下型环绕,5=衬于文字下方,6=浮于文字上方</param> /// <param name="horizontalcenter">水平居中,仅对wrapType=0生效</param> /// <returns></returns> private Paragraph CreateImageParagraph(string relationshipId, string picname, int picindex, int width, int height, int wrapType = 0, bool horizontalcenter = false) { Paragraph paragraph1 = new Paragraph(); ParagraphProperties paragraphProperties1 = new ParagraphProperties(); Justification justification1 = new Justification() { Val = JustificationValues.Center }; if (horizontalcenter && wrapType == 0) paragraphProperties1.Append(justification1); ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties(); RunFonts runFonts1 = new RunFonts() { Hint = FontTypeHintValues.EastAsia, EastAsiaTheme = ThemeFontValues.MinorEastAsia }; Languages languages1 = new Languages() { EastAsia = "zh-CN" }; paragraphMarkRunProperties1.Append(runFonts1); paragraphMarkRunProperties1.Append(languages1); paragraphProperties1.Append(paragraphMarkRunProperties1); BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" }; BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" }; Run run1 = new Run(); RunProperties runProperties1 = new RunProperties(); RunFonts runFonts2 = new RunFonts() { Hint = FontTypeHintValues.EastAsia, EastAsiaTheme = ThemeFontValues.MinorEastAsia }; Languages languages2 = new Languages() { EastAsia = "zh-CN" }; runProperties1.Append(runFonts2); runProperties1.Append(languages2); Drawing drawing1 = new Drawing(); Wp.Anchor anchor1 = new Wp.Anchor() { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U, SimplePos = false, RelativeHeight = 0U, BehindDoc = false, Locked = false, LayoutInCell = true, AllowOverlap = true }; Wp.Inline inline1 = new Wp.Inline() { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U }; DocumentFormat.OpenXml.OpenXmlCompositeElement anchorline = anchor1; if (wrapType == 0) anchorline = inline1; Wp.SimplePosition simplePosition1 = new Wp.SimplePosition() { X = 0L, Y = 0L }; Wp.HorizontalPosition horizontalPosition1 = new Wp.HorizontalPosition() { RelativeFrom = Wp.HorizontalRelativePositionValues.Column }; Wp.PositionOffset positionOffset1 = new Wp.PositionOffset(); positionOffset1.Text = "0"; horizontalPosition1.Append(positionOffset1); Wp.VerticalPosition verticalPosition1 = new Wp.VerticalPosition() { RelativeFrom = Wp.VerticalRelativePositionValues.Paragraph }; Wp.PositionOffset positionOffset2 = new Wp.PositionOffset(); positionOffset2.Text = "0"; verticalPosition1.Append(positionOffset2); Wp.Extent extent1 = new Wp.Extent() { Cx = (long)(width * 0.0264583 * 360000), Cy = (long)(height * 0.0264583 * 360000) }; Wp.EffectExtent effectExtent1 = new Wp.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }; DocumentFormat.OpenXml.OpenXmlElement wrap1 = null; var wrapPolygon1 = new Wp.WrapPolygon(); var startPoint1 = new Wp.StartPoint() { X = 0L, Y = 0L }; var lineTo1 = new Wp.LineTo() { X = 0L, Y = 21405L }; var lineTo2 = new Wp.LineTo() { X = 21501L, Y = 21405L }; var lineTo3 = new Wp.LineTo() { X = 21501L, Y = 0L }; var lineTo4 = new Wp.LineTo() { X = 0L, Y = 0L }; wrapPolygon1.Append(startPoint1); wrapPolygon1.Append(lineTo1); wrapPolygon1.Append(lineTo2); wrapPolygon1.Append(lineTo3); wrapPolygon1.Append(lineTo4); switch (wrapType) { case 1: wrap1 = new Wp.WrapSquare() { WrapText = Wp.WrapTextValues.BothSides }; break; case 2: wrap1 = new Wp.WrapTight() { WrapText = Wp.WrapTextValues.BothSides }; wrap1.Append(wrapPolygon1); break; case 3: wrap1 = new Wp.WrapThrough() { WrapText = Wp.WrapTextValues.BothSides }; wrap1.Append(wrapPolygon1); break; case 4: wrap1 = new Wp.WrapTopBottom(); break; case 5: wrap1 = new Wp.WrapNone(); anchor1.BehindDoc = true; break; case 6: wrap1 = new Wp.WrapNone(); anchor1.BehindDoc = false; break; } Wp.DocProperties docProperties1 = new Wp.DocProperties() { Id = (uint)picindex, Name = "Picture " + picindex, Description = picname }; Wp.NonVisualGraphicFrameDrawingProperties nonVisualGraphicFrameDrawingProperties1 = new Wp.NonVisualGraphicFrameDrawingProperties(); A.GraphicFrameLocks graphicFrameLocks1 = new A.GraphicFrameLocks() { NoChangeAspect = true }; graphicFrameLocks1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); nonVisualGraphicFrameDrawingProperties1.Append(graphicFrameLocks1); A.Graphic graphic1 = new A.Graphic(); graphic1.AddNamespaceDeclaration("a", "http://schemas.openxmlformats.org/drawingml/2006/main"); A.GraphicData graphicData1 = new A.GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }; Pic.Picture picture1 = new Pic.Picture(); picture1.AddNamespaceDeclaration("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); Pic.NonVisualPictureProperties nonVisualPictureProperties1 = new Pic.NonVisualPictureProperties(); Pic.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Pic.NonVisualDrawingProperties() { Id = (uint)picindex, Name = "Picture " + picindex, Description = picname }; Pic.NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new Pic.NonVisualPictureDrawingProperties(); A.PictureLocks pictureLocks1 = new A.PictureLocks() { NoChangeAspect = true }; nonVisualPictureDrawingProperties1.Append(pictureLocks1); nonVisualPictureProperties1.Append(nonVisualDrawingProperties1); nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1); Pic.BlipFill blipFill1 = new Pic.BlipFill(); A.Blip blip1 = new A.Blip() { Embed = relationshipId }; A.Stretch stretch1 = new A.Stretch(); A.FillRectangle fillRectangle1 = new A.FillRectangle(); stretch1.Append(fillRectangle1); blipFill1.Append(blip1); blipFill1.Append(stretch1); Pic.ShapeProperties shapeProperties1 = new Pic.ShapeProperties(); A.Transform2D transform2D1 = new A.Transform2D(); A.Offset offset1 = new A.Offset() { X = 0L, Y = 0L }; A.Extents extents1 = new A.Extents() { Cx = (long)(width * 0.0264583 * 360000), Cy = (long)(height * 0.0264583 * 360000) }; transform2D1.Append(offset1); transform2D1.Append(extents1); A.PresetGeometry presetGeometry1 = new A.PresetGeometry() { Preset = A.ShapeTypeValues.Rectangle }; A.AdjustValueList adjustValueList1 = new A.AdjustValueList(); presetGeometry1.Append(adjustValueList1); shapeProperties1.Append(transform2D1); shapeProperties1.Append(presetGeometry1); picture1.Append(nonVisualPictureProperties1); picture1.Append(blipFill1); picture1.Append(shapeProperties1); graphicData1.Append(picture1); graphic1.Append(graphicData1); anchorline.Append(simplePosition1); anchor1.Append(horizontalPosition1); anchor1.Append(verticalPosition1); anchorline.Append(extent1); anchorline.Append(effectExtent1); if (wrap1 != null) anchorline.Append(wrap1); anchorline.Append(docProperties1); anchorline.Append(nonVisualGraphicFrameDrawingProperties1); anchorline.Append(graphic1); drawing1.Append(anchorline); run1.Append(runProperties1); run1.Append(drawing1); paragraph1.Append(paragraphProperties1); paragraph1.Append(bookmarkStart1); paragraph1.Append(bookmarkEnd1); paragraph1.Append(run1); return paragraph1; }
其他补充内容:
使用Open XML SDK 2.5将图像添加到/ word / media文件夹
你必须自己创建图像的包部分.
MainDocumentPart类的AddImagePart()成员函数
始终将图像存储在/ media文件夹中.
下面的代码显示了如何将图像插入/ word / media文件夹
使用以下步骤:
>创建一个包含路径Uri设置为/ word / media的PackagePart.
>将图像数据输入包装部件.
>为图像创建PackageReleationship.
>使用PackageReleationship的ID来引用图像word文档.
我已经复制了AddImageToBody()函数的代码
public static void InsertAPicture(string document, string fileName) { using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true)) { MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; Uri imageUri = new Uri("/word/media/" + System.IO.Path.GetFileName(fileName), UriKind.Relative); // Create "image" part in /word/media // Change content type for other image types. PackagePart packageImagePart = wordprocessingDocument.Package.CreatePart(imageUri, "Image/jpeg"); // Feed data. byte[] imageBytes = File.ReadAllBytes(fileName); packageImagePart.GetStream().Write(imageBytes, 0, imageBytes.Length); PackagePart documentPackagePart = mainPart.OpenXmlPackage.Package.GetPart(new Uri("/word/document.xml", UriKind.Relative)); Console.Out.WriteLine(documentPackagePart.Uri); // URI to the image is relative to releationship document. PackageRelationship imageReleationshipPart = documentPackagePart.CreateRelationship( new Uri("media/" + System.IO.Path.GetFileName(fileName), UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"); AddImageToBody(wordprocessingDocument, imageReleationshipPart.Id); } } private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId) { var element = new Drawing( new DW.Inline( new DW.Extent() { Cx = 990000L, Cy = 792000L }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 1" }, new DW.NonVisualGraphicFrameDrawingProperties( new A.GraphicFrameLocks() { NoChangeAspect = true }), new A.Graphic( new A.GraphicData( new PIC.Picture( new PIC.NonVisualPictureProperties( new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = "New Bitmap Image.jpg" }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = relationshipId, CompressionState = A.BlipCompressionValues.Print }, new A.Stretch( new A.FillRectangle())), new PIC.ShapeProperties( new A.Transform2D( new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = 990000L, Cy = 792000L }), new A.PresetGeometry( new A.AdjustValueList() ) { Preset = A.ShapeTypeValues.Rectangle })) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" }); wordDoc.MainDocumentPart.Document.Body.AppendChild( new DocumentFormat.OpenXml.Wordprocessing.Paragraph( new DocumentFormat.OpenXml.Wordprocessing.Run(element))); }