![](/img/trans.png)
[英]When embedding RTF file into DOCX file using OpenXML, embedded contents don't display in some viewers
[英]Embed contents of a RTF file into a DOCX file using OpenXML SDK
在我们旧的基于MSWord-97的系统中,我们使用COM与.doc文件交互,并嵌入OLE对象,因此嵌入的文档在父级中可见(而不是图标)。
我们用一个使用OpenXML SDK的系统替换它,因为它需要在我们的服务器上使用Word,这会生成.docx文件。 但是我们仍然需要将RTF文件的内容嵌入到生成的DOCX中...具体来说,我们用文件的内容替换书签。
我在网上找到了一些例子,但它们都有所不同。 当我在Word中创建一个简单的示例并查看XML时,有很多东西可以定位/显示嵌入对象的可视化表示,而嵌入本身似乎并不太可怕。 最简单的方法是什么?
你可以嵌入的内容RTF
文档转换为OpenXML的DOCX
使用文件AltChunk
锚外部内容。 AltChunk
( w:altChunk
)元素指定OpenXML WordprocessingML文档中的位置,以插入外部内容(如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();
}
如果要将Unicode RTF
字符串嵌入到DOCX
文件中,则必须转义Unicode字符。 有关示例,请参阅以下stackoverflow答案 。
当您遇到错误“文件已损坏 ”时,请确保您使用Dispose()
或Close()
WordprocessingDocument
。 如果您没有Close()文档,那么w:altchunk
不会存储在Document.xml.rels文件中。
这个家伙似乎已经用他自己的问题和答案弄明白我如何使用OpenXml 2.0将任何文件类型嵌入到Microsoft Word中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.