如何使用Java对 Word 文档中的文本应用边框?
Java库 Apache POI 将用于在Java中为 Word 文档中的文本应用边框。 Apache POI 是 Apache Software Foundation 运行的一个项目,之前是 Jakarta Project 的一个子项目,提供纯Java库,用于读写 Microsoft Office 格式的文件,例如 Word、PowerPoint 和 Excel。使用 Apache 指南为 Windows/Linux 系统安装 Apache POI 库。
方法:
- 使用 Apache POI 包中的 XWPFDocument 创建一个空的文档对象。
- 创建一个 FileOutputStream 对象以将 Word 文档保存在系统中所需的路径/位置。
- 在文档中使用 XWPFParagraph 对象创建一个段落。
- 将边框应用于段落。
- 在段落中使用 XWPFRun 对象创建文本行。
插图:示例输入图像
执行:
- 第 1 步:创建一个空白文档
- 第二步:获取当前工作目录的路径,在运行程序的同一目录下创建PDF文件。
- 第 3 步:创建具有指定路径的文件对象。
- 第 4 步:创建一个段落。
- 第五步:设置边框。
- 第 6 步:保存对文档的更改。
- 步骤 7:关闭连接。
例子:
Java
// Java Program to apply borders to the text
// in a Word document
// Importing inout output classes
import java.io.*;
// importing Apache POI environment packages
import org.apache.poi.xwpf.usermodel.*;
// Class-BorderText
public class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Step 1: Creating a blank document
XWPFDocument document = new XWPFDocument();
// Step 2: Getting path of current working directory
// to create the pdf file in the same directory of
// the running java program
String path = System.getProperty("user.dir");
path += "/BorderText.docx";
// Step 3: Creating a file object with the path specified
FileOutputStream out
= new FileOutputStream(new File(path));
// Step 4: Create a paragraph
XWPFParagraph paragraph
= document.createParagraph();
// Step 5: Setting borders
// Set bottom border to paragraph
paragraph.setBorderBottom(Borders.DASHED);
// Set left border to paragraph
paragraph.setBorderLeft(Borders.DASHED);
// Set right border to paragraph
paragraph.setBorderRight(Borders.DASHED);
// Set top border to paragraph
paragraph.setBorderTop(Borders.DASHED);
XWPFRun line = paragraph.createRun();
line.setText(
"Whether programming excites you or you feel stifled"
+ ", wondering how to prepare for interview questions"
+ " or how to ace data structures and algorithms"
+ ", GeeksforGeeks is a one-stop solution.");
// Step 6: Saving changes to document
document.write(out);
// Step 7: Closing the connections
out.close();
document.close();
// Display message on console to illustrate
// successful execution of the program
System.out.println(
"Word Document with Border Text created successfully!");
}
}
输出:
Word Document with Border Text created successfully!
Text is inserted in the same Word document and the border is successfully applied to the same text in a Word while comparing output image with sample input image taken as illustration to show changes to it after the implementation.