如何在Microsoft Word占位符中插入html

时间:2013-09-23 06:18:34

标签: html asp.net openxml openxml-sdk

我遇到这种情况:

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

我正在使用OpenXml SDK写入文档,我尝试了HtmlToOpenXml,所以我可以阅读html。

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

1 个答案:

答案 0 :(得分: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());
            }