1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
| using Microsoft.AspNetCore.Mvc; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; using DocumentFormat.OpenXml.Wordprocessing; using System.Xml; using System.Xml.Xsl; using System.Text; using System.IO; using System.Xml.Linq;
public class ConvertRequest { public List<string> MathmlList { get; set; } public string OutputFilePath { get; set; } }
namespace OpenXmlValidatorService.Controllers { [Route("api/[controller]")] [ApiController] public class ValidatorController : ControllerBase { private readonly ILogger<ValidatorController> _logger; private readonly DateTime _startTime;
public ValidatorController(ILogger<ValidatorController> logger) { _logger = logger; _startTime = DateTime.Now; }
[HttpPost("validate")] public async Task<IActionResult> ValidateDocumentFromMathML([FromBody] string mathml) {
_logger.LogInformation($"接收到参数:{mathml}"); try { string outputDirectory = "/app/mathml_doc/"; string fileName = Guid.NewGuid().ToString() + ".docx"; string tempFilePath = Path.Combine(outputDirectory, fileName); ConvertToDocx(mathml, tempFilePath);
_logger.LogInformation("文档生成成功,开始验证:{FilePath}", tempFilePath);
using (var doc = WordprocessingDocument.Open(tempFilePath, false)) { OpenXmlValidator validator = new OpenXmlValidator(); var errors = validator.Validate(doc);
if (errors.Any()) { _logger.LogWarning("文档验证发现 {ErrorCount} 个错误", errors.Count()); foreach (var error in errors) { _logger.LogDebug("错误描述: {Description}, 节点路径: {Node}, 部件: {Part}", error.Description, error.Node, error.Part?.Uri);
if (error.Part != null && error.Part.Uri.ToString() == "/word/document.xml") { if (error.Description.Contains("math") || error.Description.Contains("Math")) { _logger.LogError("检测到公式渲染问题:{Description}", error.Description); return Ok(new { code = 400, message = tempFilePath }); } } } } _logger.LogInformation("文档验证通过:{FilePath}", tempFilePath); return Ok(new { code = 200, message = "文档符合 Open XML 规范" }); } } catch (Exception ex) { _logger.LogError(ex, "验证时发生异常:{Message}", ex.Message); return StatusCode(StatusCodes.Status500InternalServerError, new { code = 500, message = $"验证时发生异常: {ex.Message}" }); } }
[HttpGet("health")] public IActionResult GetHeartbeat() { var currentTime = DateTime.Now; var uptime = currentTime - _startTime;
var result = new { serviceName = "快降重 Open XML 文档校验 服务", statusCode = 200, timestamp = currentTime.ToString("yyyy-MM-dd HH:mm:ss"), uptime = $"{uptime.Hours}h {uptime.Minutes}m", version = "1.0.0" };
_logger.LogInformation($"心跳正常:{result}"); return Ok(result); }
[HttpPost("convertMathml")] public IActionResult ConvertToDocx([FromBody] ConvertRequest request) { if (request == null || request.MathmlList == null || request.MathmlList.Count == 0) { return Ok(new { code = 500, message = "请求体中缺少 MathML 列表或数据为空。" }); }
if (string.IsNullOrWhiteSpace(request.OutputFilePath)) { return Ok(new { code = 500, message = "请求体中缺少输出文件路径。" }); }
try { ConvertToDocxByList(request.MathmlList, request.OutputFilePath); return Ok(new { code = 200, message = "文档生成成功" }); }
catch (System.Exception ex) { return Ok(new { code = 500, message = $"文档生成失败:{ex.Message}" }); } }
public static void ConvertToDocx(string mathml, string outputFilePath) { string xsltPath = "./MML2OMML.XSL"; Console.WriteLine("xsltPath: " + xsltPath); Console.WriteLine("currentPath: " + Directory.GetCurrentDirectory()); using (XmlReader reader = XmlReader.Create(new StringReader(mathml))) { XslCompiledTransform xslTransform = new XslCompiledTransform();
if (System.IO.File.Exists(xsltPath)) { xslTransform.Load(xsltPath); } else { Console.WriteLine("XSLT 文件未找到,请确保文件路径正确!" + Directory.GetCurrentDirectory()); return; }
using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true };
using (XmlWriter xw = XmlWriter.Create(ms, settings)) { xslTransform.Transform(reader, xw); ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms, Encoding.UTF8); string officeML = sr.ReadToEnd();
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(outputFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { var mainPart = wordDoc.AddMainDocumentPart(); mainPart.Document = new Document(new Body());
DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(); Console.WriteLine("OriginInnerXML: " + officeML); officeML = officeML.Replace("<m:e />", "<m:e><m:r><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math' /></w:rPr><m:t xml:space='preserve'> </m:t></m:r></m:e>"); paragraph.InnerXml = officeML; Console.WriteLine("InnerXML: " + officeML);
DocumentFormat.OpenXml.Math.OfficeMath om = (DocumentFormat.OpenXml.Math.OfficeMath)paragraph.GetFirstChild<DocumentFormat.OpenXml.Math.OfficeMath>().Clone(); DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph1 = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
paragraph1.Append(om);
mainPart.Document.Body.Append(paragraph1); mainPart.Document.Save(); }
Console.WriteLine("Word 文档生成成功!"); } } } }
public static void ConvertToDocxByList(List<string> mathmlList, string outputFilePath) {
string directoryPath = Path.GetDirectoryName(outputFilePath); if (!Directory.Exists(directoryPath)) { Console.WriteLine($"目录不存在,正在创建目录:{directoryPath}"); Directory.CreateDirectory(directoryPath); }
string xsltPath = "./MML2OMML.XSL"; Console.WriteLine("xsltPath: " + xsltPath); Console.WriteLine("currentPath: " + Directory.GetCurrentDirectory());
if (!System.IO.File.Exists(xsltPath)) { Console.WriteLine("XSLT 文件未找到,请确保文件路径正确!" + Directory.GetCurrentDirectory()); return; }
XslCompiledTransform xslTransform = new XslCompiledTransform(); xslTransform.Load(xsltPath);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(outputFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) { var mainPart = wordDoc.AddMainDocumentPart(); mainPart.Document = new Document(new Body());
foreach (string mathml in mathmlList) { using (XmlReader reader = XmlReader.Create(new StringReader(mathml))) using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings { ConformanceLevel = ConformanceLevel.Fragment, OmitXmlDeclaration = true };
using (XmlWriter xw = XmlWriter.Create(ms, settings)) { xslTransform.Transform(reader, xw); ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8)) { string officeML = sr.ReadToEnd();
Console.WriteLine("OriginInnerXML: " + officeML); DocumentFormat.OpenXml.Wordprocessing.Paragraph tempParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); officeML = AddFontStyle(officeML); officeML = officeML.Replace("<m:e />", "<m:e><m:r><w:rPr><w:rFonts w:ascii='Cambria Math' w:hAnsi='Cambria Math' /></w:rPr><m:t xml:space='preserve'> </m:t></m:r></m:e>"); tempParagraph.InnerXml = officeML; Console.WriteLine("InnerXML: " + officeML); DocumentFormat.OpenXml.Math.OfficeMath om = tempParagraph.GetFirstChild<DocumentFormat.OpenXml.Math.OfficeMath>();
if (om != null) { DocumentFormat.OpenXml.Wordprocessing.Paragraph paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); paragraph.Append(om.CloneNode(true));
mainPart.Document.Body.Append(paragraph); } else { Console.WriteLine("OfficeMath 转换失败,跳过该公式。"); } } } } }
mainPart.Document.Save(); }
Console.WriteLine("Word 文档生成成功!"); }
public static string AddFontStyle(string inputOfficeML) { Console.WriteLine("接收到的inputOfficeML: " + inputOfficeML); XDocument xmlDoc = XDocument.Parse(inputOfficeML); XNamespace m = "http://schemas.openxmlformats.org/officeDocument/2006/math"; XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
if (xmlDoc.Root != null && xmlDoc.Root.Name.Namespace != w) { xmlDoc.Root.Add(new XAttribute(XNamespace.Xmlns + "w", w.NamespaceName)); }
var rPrElements = xmlDoc.Descendants(m + "rPr").Where(rPr => !rPr.HasElements);
foreach (var rPr in rPrElements.ToList()) { rPr.ReplaceWith(new XElement(m + "rPr", new XElement(w + "rFonts", new XAttribute(w + "ascii", "Cambria Math"), new XAttribute(w + "hAnsi", "Cambria Math")))); }
return xmlDoc.ToString(); } } }
|