简体   繁体   English

是否可以使用OpenXml将RTF文本片段插入Word文档(.docx)?

[英]Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?

I'm developing a .NET C# app that needs to create a Word document, inserting fragments of RTF text which are stored in a database. 我正在开发一个.NET C#应用程序,该应用程序需要创建Word文档,插入存储在数据库中的RTF文本片段。 Does anyone know if it is possible and how this is done using OpenXml (or COM interop)? 有谁知道这是可能的,以及使用OpenXml(或COM互操作)如何完成?

I don't need to convert one complete RTF file into a Word document. 我不需要将一个完整的RTF文件转换为Word文档。 I need to programatically create a Word document and add pieces of RTF text in different places in the word document using C#. 我需要以编程方式创建Word文档,并使用C#将RTF文本片段添加到Word文档的不同位置。

You can import external content via the altChunk anchor. 您可以通过altChunk锚导入外部内容。 The altChunk anchor defines a place within a word document to insert external content such as RTF, HTML, XML, ... altChunk锚点在Word文档中定义一个位置,以插入外部内容,例如RTF,HTML,XML等。

For more information about the altChunk anchor please refer to the following MSDN article. 有关altChunk锚点的更多信息,请参考以下MSDN文章。

The following code shows how to insert a chunk of RTF into a word document using the OpenXML SDK: 以下代码显示了如何使用OpenXML SDK将RTF块插入Word文档中:

  1. Open your word document. 打开您的Word文档。
  2. Create an AlternativeFormatImportPart chunk with a unique chunk ID. 创建具有唯一块ID的AlternativeFormatImportPart块。
  3. Feed your RTF data into the chunk (I'm using a MemoryStream here). 将您的RTF数据输入到块中(我在这里使用MemoryStream )。
  4. Create an AltChunk with the same ID used to create the AlternativeFormatImportPart . 使用与创建AlternativeFormatImportPart相同的ID创建一个AltChunk
  5. Save the word document. 保存word文档。

.

static void Main(string[] args)
{
  using (WordprocessingDocument doc = WordprocessingDocument.Open(@"test.docx", true))
  {
    string altChunkId = "AltChunkId5";

    MainDocumentPart mainDocPart = doc.MainDocumentPart;
    AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
        AlternativeFormatImportPartType.Rtf, altChunkId);                

    string rtfEncodedString = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold} text.\par}";

    using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(val)))
    {
      chunk.FeedData(ms);
    }

    AltChunk altChunk = new AltChunk();
    altChunk.Id = altChunkId;

    mainDocPart.Document.Body.InsertAfter(
      altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());

    mainDocPart.Document.Save();

  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM