C# Openxml写入word图片设置为浮于文字上方
时间: 2023-08-21 12:05:44 浏览: 200
要将图片设置为浮于文字上方,可以使用OpenXML中的DrawingML元素。具体步骤如下:
1. 创建一个DrawingML元素,将其添加到文档中。
```
Drawing drawing = new Drawing();
document.MainDocumentPart.Document.Body.Append(drawing);
```
2. 创建一个Anchor元素,设置其属性和位置信息。
```
Anchor anchor = new Anchor();
anchor.DistanceFromTop = new DistanceFromTop(0);
anchor.DistanceFromBottom = new DistanceFromBottom(0);
anchor.DistanceFromLeft = new DistanceFromLeft(0);
anchor.DistanceFromRight = new DistanceFromRight(0);
anchor.SimplePositioning = new SimplePositioning();
anchor.SimplePositioning.HorizontalPosition = new HorizontalPosition() { RelativeFrom = HorizontalRelativePositionValues.Column, PositionOffset = new PositionOffset(0) };
anchor.SimplePositioning.VerticalPosition = new VerticalPosition() { RelativeFrom = VerticalRelativePositionValues.Paragraph, PositionOffset = new PositionOffset(0) };
anchor.Append(new SimplePosition() { X = 0L, Y = 0L });
```
3. 创建一个Inline元素,并将其添加到Anchor元素中。
```
Inline inline = new Inline();
inline.Extent = new Extent() { Cx = 1000000L, Cy = 1000000L };
inline.DocProperties = new DocProperties() { Id = "1", Name = "Picture 1" };
inline.Graphic = new Graphic();
inline.Graphic.GraphicData = new GraphicData() { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" };
inline.Graphic.GraphicData.AppendChild(new Pic() { NonVisualPictureProperties = new NonVisualPictureProperties() { NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 0, Name = "New Bitmap Image.jpg" }, NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties() }, BlipFill = new BlipFill() { Blip = new Blip() { Embed = "rId1" }, SourceRectangle = new SourceRectangle() }, Stretch = new Stretch() { FillRectangle = new FillRectangle() } });
anchor.AppendChild(inline);
```
4. 将图片文件添加到文档中,并将其与Inline元素关联。
```
string imagePath = "image.jpg";
ImagePart imagePart = document.MainDocumentPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(imagePath, FileMode.Open))
{
imagePart.FeedData(stream);
}
inline.Graphic.GraphicData.Pic.Blip.Embed = document.MainDocumentPart.GetIdOfPart(imagePart);
```
通过以上步骤,你可以将图片设置为浮于文字上方。
阅读全文