Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(filepath, True)
' Insert other code here.
End Using
using 语句提供典型 .Create, .Save, .Close 序列的建议备选序列。 它确保在遇到右大括号时会自动调用 Dispose 方法(Open XML SDK 用来清理资源的内部方法)。 using 语句后面的块为 using 语句中创建或指定的对象设定范围,在此示例中这个范围就是 wordprocessingDocument。 由于 Open XML SDK 中的 WordprocessingDocument 类会在实现其 System.IDisposable 的过程中自动保存和关闭对象,并且由于在您退出代码块时会自动调用 Dispose,因此只要您使用 using,就不必明确调用 Save 和 Close。
图形对象的 XML 表示形式
ISO/IEC 29500(该链接可能指向英文页面) 规范中的以下文本介绍了 Graphic Object Data 元素。
此元素指定对文档中的图形对象的引用。 此图形对象完全由选择在文档中永久保留此数据的文档作者提供。
[注意:根据使用的图形对象的类型,不是每个支持 OOXML 框架的生成应用程序都能够呈现图形对象。 注释结束]
© ISO/IEC29500: 2008.
以下 XML 架构片段定义此元素的内容
<complexType name="CT_GraphicalObjectData">
<sequence>
<any minOccurs="0" maxOccurs="unbounded" processContents="strict"/>
</sequence>
<attribute name="uri" type="xsd:token"/>
</complexType>
示例代码的工作方式
打开文档后,使用文件流将 ImagePart 对象添加到 MainDocumentPart 对象,如以下代码段所示。
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
imagePart.FeedData(stream);
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart
Dim imagePart As ImagePart = mainPart.AddImagePart(ImagePartType.Jpeg)
Using stream As New FileStream(fileName, FileMode.Open)
imagePart.FeedData(stream)
End Using
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart))
若要将图像添加到正文,请首先定义对图像的引用。
然后将引用追加到正文。 元素应位于 Run 中。
// Define the reference of the image.
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"
// Append the reference to the body. The element should be in
// a DocumentFormat.OpenXml.Wordprocessing.Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
' Define the image reference.
Dim element = New Drawing( _
New DW.Inline( _
New DW.Extent() With {.Cx = 990000L, .Cy = 792000L}, _
New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
New DW.NonVisualGraphicFrameDrawingProperties( _
New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
New A.Graphic(New A.GraphicData( _
New PIC.Picture( _
New PIC.NonVisualPictureProperties( _
New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Koala.jpg"}, _
New PIC.NonVisualPictureDrawingProperties() _
New PIC.BlipFill( _
New A.Blip( _
New A.BlipExtensionList( _
New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
New A.Stretch( _
New A.FillRectangle() _
New PIC.ShapeProperties( _
New A.Transform2D( _
New A.Offset() With {.X = 0L, .Y = 0L}, _
New A.Extents() With {.Cx = 990000L, .Cy = 792000L}), _
New A.PresetGeometry( _
New A.AdjustValueList() _
) With {.Preset = A.ShapeTypeValues.Rectangle} _
) With {.Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture"} _
) With {.DistanceFromTop = 0UI, _
.DistanceFromBottom = 0UI, _
.DistanceFromLeft = 0UI, _
.DistanceFromRight = 0UI} _
' Append the reference to the body, the element should be in
' a DocumentFormat.OpenXml.Wordprocessing.Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(New Paragraph(New Run(element)))
以下代码示例向现有 Word 文档添加一张图片。
在您的代码中,可以通过传入 Word 文档的路径和包含图片的文件路径来调用 InsertAPicture 方法。
例如,以下调用将图片"MyPic.jpg"插入到位于指定路径的"Word9.docx"文件中。
string document = @"C:\Users\Public\Documents\Word9.docx";
string fileName = @"C:\Users\Public\Documents\MyPic.jpg";
InsertAPicture(document, fileName);
Dim document As String = "C:\Users\Public\Documents\Word9.docx"
Dim fileName As String = "C:\Users\Public\Documents\MyPic.jpg"
InsertAPicture(document, fileName)
运行代码后,请检查"Word9.docx"文件以查看插入的图片。
以下是使用 C# 和 Visual Basic 编写的完整示例代码。
public static void InsertAPicture(string document, string fileName)
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
imagePart.FeedData(stream);
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
// Define the reference of the image.
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" });
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
Public Sub InsertAPicture(ByVal document As String, ByVal fileName As String)
Using wordprocessingDocument As WordprocessingDocument = WordprocessingDocument.Open(document, True)
Dim mainPart As MainDocumentPart = wordprocessingDocument.MainDocumentPart
Dim imagePart As ImagePart = mainPart.AddImagePart(ImagePartType.Jpeg)
Using stream As New FileStream(fileName, FileMode.Open)
imagePart.FeedData(stream)
End Using
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart))
End Using
End Sub
Private Sub AddImageToBody(ByVal wordDoc As WordprocessingDocument, ByVal relationshipId As String)
' Define the reference of the image.
Dim element = New Drawing( _
New DW.Inline( _
New DW.Extent() With {.Cx = 990000L, .Cy = 792000L}, _
New DW.EffectExtent() With {.LeftEdge = 0L, .TopEdge = 0L, .RightEdge = 0L, .BottomEdge = 0L}, _
New DW.DocProperties() With {.Id = CType(1UI, UInt32Value), .Name = "Picture1"}, _
New DW.NonVisualGraphicFrameDrawingProperties( _
New A.GraphicFrameLocks() With {.NoChangeAspect = True} _
New A.Graphic(New A.GraphicData( _
New PIC.Picture( _
New PIC.NonVisualPictureProperties( _
New PIC.NonVisualDrawingProperties() With {.Id = 0UI, .Name = "Koala.jpg"}, _
New PIC.NonVisualPictureDrawingProperties() _
New PIC.BlipFill( _
New A.Blip( _
New A.BlipExtensionList( _
New A.BlipExtension() With {.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"}) _
) With {.Embed = relationshipId, .CompressionState = A.BlipCompressionValues.Print}, _
New A.Stretch( _
New A.FillRectangle() _
New PIC.ShapeProperties( _
New A.Transform2D( _
New A.Offset() With {.X = 0L, .Y = 0L}, _
New A.Extents() With {.Cx = 990000L, .Cy = 792000L}), _
New A.PresetGeometry( _
New A.AdjustValueList() _
) With {.Preset = A.ShapeTypeValues.Rectangle} _
) With {.Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"} _
) With {.DistanceFromTop = 0UI, _
.DistanceFromBottom = 0UI, _
.DistanceFromLeft = 0UI, _
.DistanceFromRight = 0UI} _
' Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(New Paragraph(New Run(element)))
End Sub
Open XML SDK 2.5 类库参考