是否可以使用 OpenXml 将 RTF 文本片段插入 Word 文档 (.docx)? [英] Is it possible to insert pieces of RTF text into a Word document (.docx) using OpenXml?

查看:16
本文介绍了是否可以使用 OpenXml 将 RTF 文本片段插入 Word 文档 (.docx)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 .NET C# 应用程序,它需要创建一个 Word 文档,插入存储在数据库中的 RTF 文本片段.有谁知道这是否可能以及如何使用 OpenXml(或 COM 互操作)来完成?

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. Does anyone know if it is possible and how this is done using OpenXml (or COM interop)?

我不需要将一个完整的 RTF 文件转换为 Word 文档.我需要以编程方式创建一个 Word 文档,并使用 C# 在 Word 文档的不同位置添加 RTF 文本片段.

I don't need to convert one complete RTF file into a Word document. I need to programatically create a Word document and add pieces of RTF text in different places in the word document using C#.

推荐答案

您可以通过 altChunk 锚点导入外部内容.altChunk 锚定义了 Word 文档中要插入的位置外部内容,如 RTF、HTML、XML、...

You can import external content via the altChunk anchor. The altChunk anchor defines a place within a word document to insert external content such as RTF, HTML, XML, ...

有关 altChunk 锚点的更多信息,请参阅以下 MSDN 文章.

For more information about the altChunk anchor please refer to the following MSDN article.

以下代码展示了如何使用OpenXML SDK:

The following code shows how to insert a chunk of RTF into a word document using the OpenXML SDK:

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

.

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 = @"{
tf1ansi{fonttblf0fswiss Helvetica;}f0pard This is some { 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();

  }
}

这篇关于是否可以使用 OpenXml 将 RTF 文本片段插入 Word 文档 (.docx)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆