解决Devexpress的RichEditControl控件保存为docx文件后在word里打开字体显示不正确的问题
问题复现
用Richeditcontrol编辑如下内容并保存为.docx文件:
用word或wps打开的效果:
寻找原因
我用word编辑个一样内容的文件,将这两个文件的扩展名修改为zip,解压后经过对比,发现document.xml
文件这里不同:
我用bing搜索了这个关键字,搜索到了相关文档,奈何和谐社会。
解决办法
增加一个“保存“按钮,保存为docx文件后,把其中的document.xml
文件修改之。代码如下:
using DevExpress.XtraRichEdit;
using Ionic.Zip;
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
namespace RicheditcontrolFontDemo
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void barButtonItemSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog
{
Filter = "doc|*.docx"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
this.richEditControl.SaveDocument(sfd.FileName, DocumentFormat.OpenXml);
MondifyFonts(sfd.FileName);
}
}
private void MondifyFonts(string path)
{
using (ZipFile zip = new ZipFile(path)) // DotNetZip
{
var entry = zip.First(e => e.FileName == "word/document.xml");
string tempPath = DateTime.Now.ToString("yyyyMMddHHmmssfff");
entry.Extract(tempPath);
AddEastAsiaFont($"{tempPath}//word/document.xml");
zip.RemoveEntry(entry);
zip.AddFile($"{tempPath}//word/document.xml", "word");
zip.Save();
Directory.Delete(tempPath, true);
}
}
private void AddEastAsiaFont(string file)
{
XmlDocument doc = new XmlDocument();
XmlNamespaceManager xmlm = new XmlNamespaceManager(doc.NameTable);
xmlm.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
doc.Load(file);
var nodes = doc.SelectNodes("//w:rFonts", xmlm);
foreach (XmlNode node in nodes)
{
if (!AnyEastAsiaAttribute(node))
{
string fontName = GetFontName(node);
if (fontName != null)
{
XmlAttribute atr = doc.CreateAttribute("w", "eastAsia", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
atr.Value = fontName;
node.Attributes.Append(atr);
}
}
}
doc.Save(file);
}
private string GetFontName(XmlNode node)
{
foreach (XmlAttribute item in node.Attributes)
{
if (item.Name == "w:ascii" || item.Name == "w:hAnsi")
{
return item.Value;
}
}
return null;
}
private bool AnyEastAsiaAttribute(XmlNode node)
{
foreach (XmlAttribute item in node.Attributes)
{
if (item.Name == "w:eastAsia")
{
return true;
}
}
return false;
}
}
}
欢迎转载,转载请注明出处
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2011-12-17 好书推荐——《启动大脑》