<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version> <!-- 最後開源版本 -->
</dependency>
<!-- 或引入 itext-rtf.jar -->
import com.lowagie.text.*;
import com.lowagie.text.rtf.RtfWriter2;
import java.awt.Color;
import java.io.FileOutputStream;
public class RTFCreate {
public static void main(String[] args) throws Exception {
Document document = new Document(PageSize.A4);
RtfWriter2.getInstance(document, new FileOutputStream("C:/World.rtf"));
document.open();
// 1. 添加段落(支持中文)
Font chineseFont = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", 12);
document.add(new Paragraph("Hello World! 您好!hehe!", chineseFont));
// 2. 構建表格
Table table = new Table(3);
table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(5);
// 表頭跨列
Cell header = new Cell("Header");
header.setHeader(true);
header.setColspan(3);
table.addCell(header);
table.endHeaders(); // 標記表頭結束
// 普通單元格
table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
// 跨行跨列單元格
Cell big = new Cell("Big Cell");
big.setRowspan(2);
big.setColspan(2);
big.setBorderColor(new Color(255, 0, 0));
table.addCell(big);
table.addCell("cell test2");
document.add(table);
document.close();
System.out.println("RTF generated successfully.");
}
}
| 需求 | iText 類/方法 | 備註 |
|---|---|---|
| 創建文檔 | new Document(PageSize.A4) |
可設置邊距 new Document(PageSize.A4, 36, 36, 54, 36) |
| 綁定輸出流 | RtfWriter2.getInstance(doc, outputStream) |
PDF 對應 PdfWriter.getInstance |
| 中文字體 | FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", size) |
需 iTextAsian.jar 支持 CJK 字體 |
| 表格創建 | new Table(columnCount) |
舊版 API,新版建議用 PdfPTable(僅 PDF) |
| 單元格合併 | cell.setRowspan(n) / setColspan(n) |
需在 addCell 前設置 |
| 表頭重複 | cell.setHeader(true); table.endHeaders() |
跨頁打印時表頭自動重複 |
FontFactory.register("simsun.ttc"))或使用 iTextAsian 內建字體映射。Document 會在內存構建完整模型再寫入,超大報表建議分頁生成多個 RTF 再合併。RtfWriter2,若需維護舊項目請鎖定 2.1.7;新項目建議 Apache POI (XWPF) 生成 .docx。// 假設有 List
iText 2.x 時代的 RtfWriter2 提供了極簡的「Java 對象 → RTF」映射能力。掌握 Document/Table/Cell 三大核心模型、字體註冊、跨頁表頭、合併單元格四大技巧,即可覆蓋 90% 業務導出 Word 需求。對於現代項目,推薦遷移至 Apache POI XWPF (.docx) 或 docx4j,獲得更好的 OOXML 標準支持與維護活躍度。