簡體   English   中英

使用OpenXML SDK將RTF文件的內容嵌入到DOCX文件中

[英]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錨外部內容。 AltChunkw: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM