我有这种情况:
用户的页面上有一个编辑器,他输入文本(带有颜色,格式,超链接,还可以添加图片)。当他单击“提交”时,必须将来自编辑器的数据(格式正确)发送到Microsoft Office Word文档中的特定占位符。
我正在使用OpenXml SDK编写文档,并且尝试使用HtmlToOpenXml,以便可以阅读html。
我使用HtmlToOpenXml,并从html字符串(来自用户)中找到了几个段落,现在我必须将它们插入内容控件中。您知道如何找到控件并将其附加到控件中(如果可能)
我设法解决了这是我使用的代码
//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());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句