【发布时间】:2015-01-21 09:18:38
【问题描述】:
我正在使用 System.IO.Packaging 和 Open XML SDK 创建一个新的 docx。在我的 docx 中,我想嵌入其他现有的 docx 文件。结果应该与我在 Microsoft Word 中手动执行的结果相同。每个嵌入的 docx 文件的 docx 中应该有一个图标。在图标中,我想添加嵌入的 docx 文件的名称。对于要嵌入的所有文件,我有相同的图像。但我不知道如何在嵌入时向图像添加一些文本。
这是我目前的代码:
static void Main(string[] args)
{
const string containingDocumentPath = @"ContainingDocument.docx";
const string embeddedDocumentPath = @"EmbeddedDocument.docx";
CreatePackage(containingDocumentPath, embeddedDocumentPath);
}
private static void CreatePackage(string containingDocumentPath, string embeddedDocumentPath)
{
using (WordprocessingDocument package = WordprocessingDocument.Create(containingDocumentPath, WordprocessingDocumentType.Document))
{
AddParts(package, embeddedDocumentPath);
}
}
private static void AddParts(WordprocessingDocument parent,
string embeddedDocumentPath)
{
var mainDocumentPart = parent.AddMainDocumentPart();
GenerateMainDocumentPart().Save(mainDocumentPart);
var embeddedPackagePart =
mainDocumentPart.AddNewPart<EmbeddedPackagePart>(
"application/vnd.openxmlformats-" +
"officedocument.wordprocessingml.document",
"rId1");
GenerateEmbeddedPackagePart(embeddedPackagePart, embeddedDocumentPath);
var imagePart = mainDocumentPart.AddNewPart<ImagePart>("image/x-emf", "rId2");
GenerateImagePart(imagePart);
}
private static Document GenerateMainDocumentPart()
{
var element =
new Document(
new Body(
new Paragraph(
new Run(
new EmbeddedObject(
new Shape(
new ImageData()
{
RelationshipId = "rId2",
}
)
{
Id = "_x0000_i1025",
OptionalString = "abc",
Style = "width:16pt;height:16pt",
},
new OleObject()
{
ProgId = "Word.Document.12",
ShapeId = "_x0000_i1025",
ObjectId = "_1299573545",
Id = "rId1"
}
)
{
DxaOriginal = "1531UL",
DyaOriginal = "991UL"
}
)
)
)
);
return element;
}
public static void GenerateEmbeddedPackagePart(OpenXmlPart part, string embeddedDocumentPath)
{
byte[] embeddedDocumentBytes;
// The following code will generate an exception if an invalid
// filename is passed.
using (FileStream fsEmbeddedDocument = File.OpenRead(embeddedDocumentPath))
{
embeddedDocumentBytes = new byte[fsEmbeddedDocument.Length];
fsEmbeddedDocument.Read(embeddedDocumentBytes, 0, embeddedDocumentBytes.Length);
}
using (var writer = new BinaryWriter(part.GetStream()))
{
writer.Write(embeddedDocumentBytes);
writer.Flush();
}
}
public static void GenerateImagePart(OpenXmlPart part)
{
using (var writer = new BinaryWriter(part.GetStream()))
{
writer.Write(File.ReadAllBytes(@"Icons\MyImage.GIF"));
writer.Flush();
}
}
【问题讨论】:
-
为什么不用电动工具来做openxml?它有一种将两个或多个 docx 文件合并为一个的简单方法。 powertools.codeplex.com
标签: c# openxml-sdk embedding