本主题演示如何使用 Open XML SDK for Office 中的类以编程方式向字处理文档添加图片。
打开现有文档以进行编辑
若要打开现有文档,请实例化 类, WordprocessingDocument 如以下 using 语句所示。 在同一语句中,使用 Open(String, Boolean) 方法在指定的 filepath 处打开字处理文件,并将布尔参数设置为 true 以启用文档编辑。
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
在 v3.0.0+ 中, Close() 已删除 方法,转而依赖于 using 语句。
它确保在 Dispose() 到达右大括号时自动调用 方法。 using 语句后面的块为 using 语句中创建或指定的对象设定范围。
WordprocessingDocument由于 Open XML SDK 中的 类会自动保存并关闭对象作为其IDisposable实现的一using部分,并且由于Dispose()在退出块时会自动调用,因此无需显式调用 Save() 或 Dispose() ,只要使用 语句。
图形对象的 XML 表示形式
ISO/IEC 29500(该链接可能指向英文页面) 规范中的以下文本介绍了 Graphic Object Data 元素。
此元素指定对文档中的图形对象的引用。 此图形对象完全由选择在文档中永久保留此数据的文档作者提供。
[注意:根据使用的图形对象的类型,不是每个支持 OOXML 框架的生成应用程序都能够呈现图形对象。 注释结束]
© ISO/IEC 29500:2016
以下 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));
若要将图像添加到正文,请首先定义对图像的引用。 然后将引用追加到正文。 元素应位于 中 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"
});
if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
示例代码
以下代码示例向现有 Word 文档添加一张图片。
在代码中,可以通过传入单词文档的路径和包含图片的文件的路径来调用 InsertAPicture 方法。
例如,以下调用插入图片。
string documentPath = args[0];
string picturePath = args[1];
InsertAPicture(documentPath, picturePath);
运行代码后,查看文件以查看插入的图片。
以下是使用 C# 和 Visual Basic 编写的完整示例代码。
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.IO;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
{
if (wordprocessingDocument.MainDocumentPart is null)
{
throw new ArgumentNullException("MainDocumentPart is null.");
}
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));
}
}
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"
});
if (wordDoc.MainDocumentPart is null || wordDoc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}