#region Insert Images
public string InsertImage(XmlWriter writer, string imageType, string imageUrl)
{
// create the new image part
if (File.Exists(imageUrl))
{
FileInfo fi = new FileInfo(imageUrl);
Uri imageUri =
new Uri("/word/media/" + fi.Name,
UriKind.Relative);
package.CreateNewPart(imageUri, imageType,
imageUrl);
// create the relationship between the document and the image
string ImageRelId = package.CreateInternalRelationship(
new Uri(@"/word/document.xml", UriKind.Relative),
imageUri, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
InsertImage(writer, ImageRelId);
return ImageRelId;
}
else return "";
}
///
///
///
///
/// "image/jpeg"
///
public string InsertImage(XmlWriter writer, string imageId, string imageType, byte[] image)
{
// create the new image part
Uri imageUri =
new Uri("/word/media/" + imageId,
UriKind.Relative);
package.CreateNewPart(imageUri, imageType,
image);
// create the relationship between the document and the image
string ImageRelId = package.CreateInternalRelationship(
new Uri(@"/word/document.xml", UriKind.Relative),
imageUri, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");
InsertImage(writer, ImageRelId);
return ImageRelId;
}
public void InsertImage(XmlWriter writer, string imageId)
{
XmlDocument drawingXml = new XmlDocument();
drawingXml.LoadXml(
string.Format(Properties.Resources.DrawingTemplate,
imageId));
writer.WriteStartElement(Prefixes.WordprocessingML, "p",
Namespaces.WordprocessingML);
writer.WriteStartElement(Prefixes.WordprocessingML, "r",
Namespaces.WordprocessingML);
drawingXml.DocumentElement.WriteContentTo(writer);
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion
以下为调用方法
public static void Run()
{
PackageHelper package;
WordprocessingDoc xmlDoc = new WordprocessingDoc();
package = xmlDoc.Package;
// load the document package part into an XmlDocument
Uri documentUri =
new Uri(@"/word/document.xml", UriKind.Relative);
XmlDocument documentXml =
package.GetWritablePart(documentUri);
XPathNavigator documentNav = documentXml.CreateNavigator().SelectSingleNode("w:document/w:body/w:p", Namespaces.NamespaceManager);
using (XmlWriter writer = documentNav.ReplaceRange(documentNav))
{
xmlDoc.InsertImage(writer, "image/bmp", imgPath + "8.bmp");
xmlDoc.InsertImage(writer, "image/bmp", imgPath + "9.bmp");
}
// write the document into the package part
package.SavePart(documentUri, documentXml);
// write the package to the a file
package.Save(docPath + "CellReportTest.docx");
}