1
0

More than 3 years have passed since last update.

Java Word文書で数式を追加

Posted at

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

下準備

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

f:id:lendoris:20210825151531p:plain

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

f:id:lendoris:20210825151541p:plain

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

実行結果

f:id:lendoris:20210825151622p:plain

 

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0