本教程包含有关如何使用 Java 在 Word 中插入页码的所有信息,提供步骤和可运行的示例代码以及详细说明。给定的步骤描述了完整的程序逻辑,可以遵循该逻辑编写一个简单的应用程序,以使用 Java 在 Word 中添加页码,然后将生成的文件保存为 DOCX 或 DOC 文件格式。您还将学习在 Word 文件中移动到页眉和页脚部分的不同部分。
使用 Java 在 Word 中插入页码的步骤
- 采取必要的步骤在您的应用程序中添加 Aspose.Words for Java
- 使用 Document 类对象加载源 Word 文件以添加页码
- 使用加载的 Word 文件实例化 DocumentBuilder 类对象
- 使用 DocumentBuilder 对象将控件移动到主要页脚部分
- 添加 PAGE 和 NUMPAGES 等字段以及标题和分隔符
- 在页脚中添加页码后保存生成的 Word 文件
这些步骤通过共享 DocumentBuilder 类中可用于在 Word 文件的页眉或页脚中添加页码的方法和属性的详细信息,描述如何使用 Java 将页码放入 Word。首先,我们加载源 Word 文件并实例化 DocumentBuilder 类对象,该对象包含诸如移动到文档的不同部分以处理内容以及根据要求在页眉和页脚中添加不同字段等功能。
使用 Java 插入页码的代码
import com.aspose.words.Document; | |
import com.aspose.words.DocumentBuilder; | |
import com.aspose.words.HeaderFooterType; | |
public class AsposeTest { | |
public static void main(String[] args) throws Exception {//Main function to add page number | |
// Instantiate the license | |
com.aspose.words.License license = new com.aspose.words.License(); | |
license.setLicense("Aspose.Total.lic"); | |
// Open the source file | |
Document wordFile = new Document("TestFile.docx"); | |
// Instantiate DocumentBuilder using the loaded document | |
DocumentBuilder fileBuilder = new DocumentBuilder(wordFile); | |
// Move control to the primary footer section | |
fileBuilder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY); | |
// Write text for clarity | |
fileBuilder.write("Page "); | |
// Insert a field | |
fileBuilder.insertField("PAGE", ""); | |
fileBuilder.write(" of "); | |
// Insert field for the number of pages | |
fileBuilder.insertField("NUMPAGES", ""); | |
// Save the resultant file | |
wordFile.save("OutputWithPageNumbers.docx"); | |
System.out.println("Done"); | |
} | |
} |
此代码演示如何使用 Java 在 Word 中的页面上放置数字,使用不同的类和方法,例如 moveToHeaderFooter() 方法用于通过使用 FOOTER_PRIMARY 枚举器将控件移动到页脚,但是,您也可以使用 HEADER_PRIMARY、HEADER_FIRST、 HEADER_EVEN、FOOTER_EVEN 和 FOOTER_FIRST。同样,您可以使用 insertField() 方法以及使用 write() 方法添加标题和分隔符的选项来添加其他字段,例如 NUMWORDS、NUMCHARS 等。
在本文中,我们学习了使用 Java 在 Word 中插入页码。如果您想了解在 Word 文档中添加评论的过程,请参阅 如何使用 Java 在 Word 中添加注释 上的文章。