0
我正在使用System.IO.Packaging和Open XML SDK创建新的docx。在我的docx中,我想嵌入其他现有的docx文件。结果应该与我在Microsoft Word中手动完成的结果相同。每个嵌入式docx文件的docx中应该有一个图标。在图标中,我想添加嵌入式docx文件的名称。对于要嵌入的所有文件,我拥有相同的图像。但我不知道如何在嵌入时向图片添加一些文字。如何在将Word文档嵌入到单个文档中时使用文本创建图像
这是我到目前为止的代码:
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文件合并为一个。 https://powertools.codeplex.com/ – 2015-01-22 04:15:48