Wordは数式を入力することができます。数式の用法を使いこなせば、とても便利なツールになるはずだと思いますので、今回は、Spire.Doc for Javaという使いやすいライブラリを活用して、WordでLatex 数式とMathMLCodeを挿入する方法を紹介します。
下準備
1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。
2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。
```JAVA import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.omath.*;public class Test {
public static void main(String[] args){
//Word obejctを作成し,sectionを追加します。
Document doc = new Document();
Section section = doc.addSection();
//段落を追加します。
Paragraph paragraph = section.addParagraph();
//Latex 数式を挿入します。
OfficeMath officeMath = new OfficeMath(doc);
paragraph.getItems().add(officeMath);
officeMath.fromLatexMathCode("x^{2}+\\sqrt{{x^{2}+1}}+1");
//段落2を追加します。
Paragraph paragraph2 = section.addParagraph();
//MathMLCodeを挿入します。
OfficeMath officeMath2 = new OfficeMath(doc);
paragraph2.getItems().add(officeMath2);
officeMath2.fromMathMLCode("<mml:math xmlns:mml=\"http://www.w3.org/1998/Math/MathML\" xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:msqrt><mml:msup><mml:mrow><mml:mi>x</mml:mi></mml:mrow><mml:mrow><mml:mn>2</mml:mn></mml:mrow></mml:msup><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:msqrt><mml:mo>+</mml:mo><mml:mn>1</mml:mn></mml:math>");
//保存します。
String result = "output/addMathEquation.docx";
doc.saveToFile(result, FileFormat.Docx_2013);
}
}
<h4><strong>実行結果</strong></h4>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210825/20210825151622.png" alt="f:id:lendoris:20210825151622p:plain" width="554" height="323" loading="lazy" title="" class="hatena-fotolife" itemprop="image" /></p>
<p> </p>