1

我有这种情况:

用户在他的页面上有一个编辑器,他输入文本(带有颜色、格式、超链接,他还可以添加图片)。当他单击提交时,必须将来自编辑器的数据(具有正确格式)发送到 Microsoft Office Word 文档中的特定占位符。

我正在使用 OpenXml SDK 编写文档,并尝试了 HtmlToOpenXml 以便可以读取 html。

我使用 HtmlToOpenXml 并从 html 字符串(来自用户)中删除了几个段落,现在我必须将它们插入到内容控件中。你知道我怎样才能找到控件并将它们附加到其中(如果可能的话)

4

1 回答 1

0

我设法解决了这个问题,这是我使用的代码

            //name of the file which will be saved
            const string filename = "test.docx";
            //html string to be inserted and rendered in the word document
            string html = @"<b>Test</b>"; 
            //the Html2OpenXML dll supports all the common html tags

            //open the template document with the content controls in it(in my case I used Richtext Field Content Control)
            byte[] byteArray = File.ReadAllBytes("..."); // template path

            using (MemoryStream generatedDocument = new MemoryStream())
            {
                generatedDocument.Write(byteArray, 0, byteArray.Length);

                using (WordprocessingDocument doc = WordprocessingDocument.Open(generatedDocument, true))
                {

                    MainDocumentPart mainPart = doc.MainDocumentPart;
                    //just in case
                    if (mainPart == null)
                    {
                        mainPart = doc.AddMainDocumentPart();
                        new Document(new Body()).Save(mainPart);
                    }

                    HtmlConverter converter = new HtmlConverter(mainPart);
                    Body body = mainPart.Document.Body;

                    //sdtElement is the Content Control we need. 
                    //Html is the name of the placeholder we are looking for
                    SdtElement sdtElement = doc.MainDocumentPart.Document.Descendants<SdtElement>()
                        .Where(
                            element =>
                            element.SdtProperties.GetFirstChild<SdtAlias>() != null &&
                            element.SdtProperties.GetFirstChild<SdtAlias>().Val == "Html").FirstOrDefault();

                    //the HtmlConverter returns a set of paragraphs.
                    //in them we have the data which we want to insert in the document with it's formating
                    //After that we just need to append all paragraphs to the Content Control and save the document
                    var paragraphs = converter.Parse(html);

                    for (int i = 0; i < paragraphs.Count; i++)
                    {
                        sdtElement.Append(paragraphs[i]);
                    }

                    mainPart.Document.Save();
                }

                File.WriteAllBytes(filename, generatedDocument.ToArray());
            }
于 2013-09-26T06:18:14.207 回答