Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

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

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#.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, ...

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

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

  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();

  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...