关于java:Java在Word中插入上标和下标

2次阅读

共计 2285 个字符,预计需要花费 6 分钟才能阅读完成。

前言

在某些状况下,你可能须要在 Microsoft Word 中插入上标和下标。例如,当你正在创立一个波及迷信公式的学术文件时。在这篇文章中,你将学习如何应用 Spire.Doc for Java 库在 Word 文档中插入上标和下标。


程序环境

装置 Spire.Doc for Java

首先,你须要在你的 Java 程序中增加 Spire.Doc.jar 文件作为依赖项。该 JAR 文件能够从这个链接下载。如果你应用 Maven,你能够通过在我的项目的 pom.xml 文件中增加以下代码,在你的应用程序中轻松导入该 JAR 文件。

代码示例

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>10.9.8</version>
    </dependency>
</dependencies>

留神:下面代码中的版本号要与下载连贯中的版本号保持一致,以体验最新性能或者防止 BUG。

应用 Java 在 Word 中插入上标和下标

步骤

  1. 创立一个 Document 实例。
  2. 应用 Document.loadFromFile() 办法加载一个 Word 文档。
  3. 应用 Document.getSections().get(sectionIndex) 办法获取特定的章节。
  4. 应用 Section.addParagraph() 办法向该局部增加一个段落。
  5. 应用 Paragraph.appendText() 办法向该段增加一般文本。
  6. 应用 Paragraph.appendText() 办法将上标或下标文本增加到段落中。
  7. 通过 TextRange.getCharacterFormat().setSubSuperScript() 办法给上标或下标文本利用上标或下标格局。
  8. 应用 Document.saveToFile() 办法保留后果文档。

代码实现

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
import com.spire.doc.fields.TextRange;

public class InsertSuperscriptAndSubscript {public static void main(String[] args){
        // 创立一个 Document 实例
        Document document = new Document();
        // 加载 Word 文档
        document.loadFromFile("Sample.docx");

        // 获取第一节
        Section section = document.getSections().get(0);

        // 增加一个段落到该节
        Paragraph paragraph = section.addParagraph();

        // 向该段增加一般文本
        paragraph.appendText("E = mc");
        // 增加上标文本到段落中
        TextRange superscriptText = paragraph.appendText("2");
        // 利用上标格局到上标文本
        superscriptText.getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);

        // 开始新的一行
        paragraph.appendBreak(BreakType.Line_Break);

        // 增加一般文本到段落
        paragraph.appendText("H");
        // 增加下标文本到该段
        TextRange subscriptText = paragraph.appendText("2");
        // 利用下标格局到下标文本
        subscriptText.getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
        // 增加一般文本到该段
        paragraph.appendText("O");

        // 设置段落中文本的字体大小
        for(Object item : paragraph.getItems())
        {if (item instanceof TextRange)
            {TextRange textRange = (TextRange)item ;
                textRange.getCharacterFormat().setFontSize(36f);
            }
        }
        // 保留后果文档
        document.saveToFile("InsertSuperscriptAndSubscript.docx", FileFormat.Docx_2013);
    }
}

效果图

提醒:该 JAR 包有免费版和商业版之分,免费版有性能和篇幅限度,篇幅很少可放心使用,若要体验残缺性能,能够申请 30 天长期收费 license 应用商业版。

—THE END—

正文完
 0