【问题标题】:OpenXML - Infopath RichText Box to Word Document gives formatting errorsOpenXML - 到 Word 文档的 Infopath RichText 框给出格式错误
【发布时间】:2013-04-16 19:03:17
【问题描述】:

我已经在 InfoPath 表单中设置了富文本框,我的程序通过 Infopath XML 解析如下:

XPathNavigator formNameNode = root.SelectSingleNode("/my:myFields/my:Responses/my:Q1", nsMgr);
string response1 = formNameNode.InnerXml;

然后使用下面的代码打开一个word文档并得到一个名为response1的纯文本内容控件:

    using (WordprocessingDocument myDoc =
WordprocessingDocument.Open(ms, true))
    {
        MainDocumentPart mainPart = myDoc.MainDocumentPart;

    List<OpenXmlElement> sdtList = InfoPathToWord.GetContentControl(mainPart.Document, "response1");
            InfoPathToWord.AddRichText(0, response1, ref mainPart, ref sdtList);
}

然后代码调用InfoPathToWord.AddRichText,如下:

public static void AddRichText(int id, string rtfValue,
          ref MainDocumentPart mainPart, ref List<OpenXmlElement> sdtList)
        {
            if (sdtList.Count != 0)
            {
                id++;
                string altChunkId = "AltChunkId" + id;
                AlternativeFormatImportPart chunk =
                  mainPart.AddAlternativeFormatImportPart(
                  AlternativeFormatImportPartType.Xhtml, altChunkId);

                using (MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(rtfValue)))
                {
                    chunk.FeedData(ms);
                    ms.Close();
                }

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                InfoPathToWord.ReplaceContentControl(sdtList, altChunk);
            }
        }

最后,altChunk 替换了“response1”

    public static void ReplaceContentControl(
      List<OpenXmlElement> sdtList, OpenXmlElement element)
    {
        if (sdtList.Count != 0)
        {
            foreach (OpenXmlElement sdt in sdtList)
            {
                OpenXmlElement parent = sdt.Parent;
                parent.InsertAfter(element, sdt);
                sdt.Remove();
            }
        }
    }

问题是它替换了文本,但格式不正确并显示“?”输出文本中的字符。 不确定它是否是由于编码引起的,我也尝试过System.Text.Encoding.UTF8.GetBytes(rtfValue), System.Text.Encoding.ASCII.GetBytes(rtfValue),但这似乎都没有帮助。

请有人告诉我我做错了什么。

提前致谢。

马夫

【问题讨论】:

    标签: openxml infopath


    【解决方案1】:

    我正在使用正则表达式在保存之前清理字符串。

    html = Regex.Replace(html, "/[\x00-\x08\x0B\x0C\x0E-\x1F\x80-\x9F]/u", "") ' 允许制表符和其他可打印字符

    Dim ms As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)) ' 创建替代格式导入部分。 将 formatImportPart 调暗为 AlternativeFormatImportPart = mainDocPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId)

    Regex to remove all special characters from string?

    更新... 经过严格的测试,我在 docx 中发现 InfoPath RTF 的字符编码问题太多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多