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