前言
在某些状况下,你可能须要在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中插入上标和下标
步骤
- 创立一个Document实例。
- 应用Document.loadFromFile()办法加载一个Word文档。
- 应用Document.getSections().get(sectionIndex)办法获取特定的章节。
- 应用Section.addParagraph()办法向该局部增加一个段落。
- 应用Paragraph.appendText()办法向该段增加一般文本。
- 应用Paragraph.appendText()办法将上标或下标文本增加到段落中。
- 通过TextRange.getCharacterFormat().setSubSuperScript()办法给上标或下标文本利用上标或下标格局。
- 应用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—
发表回复