[英]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.