您可以使用外部内容的锚点将RTF
文档的内容嵌入到 OpenXMLDOCX
文件中。( ) 元素指定 OpenXML WordprocessingML 文档中AltChunk
的一个位置,用于插入外部内容,例如文档。下面的代码使用该类与该类结合将文档的内容嵌入到最后一段之后的文件中: AltChunk
w:altChunk
RTF
AltChunk
AlternativeFormatImportPart
RTF
DOCX
using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(@"your_docx_file.docx", true))
{
string altChunkId = "AltChunkId5";
MainDocumentPart mainDocPart = wordDocument.MainDocumentPart;
AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Rtf, altChunkId);
// Read RTF document content.
string rtfDocumentContent = File.ReadAllText("your_rtf_document.rtf", Encoding.ASCII);
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(rtfDocumentContent)))
{
chunk.FeedData(ms);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
// Embed AltChunk after the last paragraph.
mainDocPart.Document.Body.InsertAfter(
altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());
mainDocPart.Document.Save();
}
如果要将 UnicodeRTF
字符串嵌入到DOCX
文件中,则必须转义 Unicode 字符。有关示例,请参阅以下stackoverflow 答案。
当您遇到错误“文件已损坏”时,请确保您Dispose()
或. 如果您不关闭()该文档,则该文档的关系不会存储在Document.xml.rels文件中。Close()
WordprocessingDocument
w:altchunk