Java Word文書で数式を追加


Wordは数式を入力することができます。数式の用法を使いこなせば、とても便利なツールになるはずだと思いますので、今回は、Spire.Doc for Javaという使いやすいライブラリを活用して、WordでLatex 数式とMathMLCodeを挿入する方法を紹介します。

下準備

1.E-iceblueの公式サイトからFree Spire.doc for Java無料版をダウンロードしてください。

2.IDEを起動して新規プロジェクトを作成してから、インストールされたファイルにあった相応しいSpire.doc.jarを参照に追加してください。

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);
    }
}

実行結果