<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
2.1.7
</dependency>
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
import java.awt.Color;
import java.io.FileOutputStream;
public class PDFCreate {
public static void main(String[] args) throws Exception {
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream("C:/HelloWorld.pdf"));
document.open();
// 中文字體支持(需 iTextAsian.jar)
Font cnFont = FontFactory.getFont("STSong-Light", "UniGB-UCS2-H", 12);
document.add(new Paragraph("Hello World! 您好!hehe!", cnFont));
// 複用表格邏輯(同 RTF 示例)
Table table = new Table(3);
table.setBorderWidth(1);
table.setBorderColor(Color.BLUE);
table.setPadding(5);
table.setSpacing(5);
Cell header = new Cell("Header");
header.setHeader(true);
header.setColspan(3);
table.addCell(header);
table.endHeaders();
// ... 添加數據行、合併單元格 ...
document.add(table);
document.close();
}
}
| 功能 | 關鍵類/方法 | 說明 |
|---|---|---|
| 頁碼/頁眉頁腳 | PdfPageEventHelper 實現 onEndPage |
Writer.setPageEvent(new MyFooter()) |
| 水印 | PdfContentByte 繪製文本/圖片,設置透明度 |
writer.getDirectContentUnder() |
| 書籤/大綱 | Chapter、Section、Anchor |
自動生成 PDF 大綱面板 |
| 表單域 | PdfFormField、TextField、ButtonField |
生成可填寫 PDF 表單 |
| 數字簽名 | PdfSignatureAppearance、PdfPKCS7 |
需簽名證書鏈 |
| 字體嵌入 | BaseFont.createFont(..., BaseFont.EMBEDDED) |
確保跨平台顯示一致 |
PdfPTable)iText 2.x 中 Table 同時服務 PDF/RTF/HTML,但 PdfPTable 針對 PDF 引擎優化,支持:
table.setWidths(new float[]{2, 3, 5})cell.setCellEvent(new MyCellEvent()) 實現斜線、背景圖等。table.setSplitLate(false) 避免最後一行孤立。// 1. 註冊系統字體(一次性)
FontFactory.register("c:/windows/fonts/simsun.ttc", "SimSun");
// 2. 創建字體對象
BaseFont bfChinese = BaseFont.createFont("SimSun", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font font = new Font(bfChinese, 12);
// 3. 使用
new Paragraph("中文內容", font);
PdfWriter 默認緩衝頁面,大文檔調用 document.close() 前定期 document.newPage() 釋放內存。Image.getInstance(url) 緩存實例,避免重複解碼。BaseFont 對象線程安全且重量級,全局單例複用。com.itextpdf.*,Table 棄用,全面轉向 PdfPTable、PdfPCell。iText 2.1.7 以 Document → PdfWriter → Table/Paragraph 經典鏈路,提供了極低門檻的 PDF 生成能力。掌握中文字體嵌入、PdfPTable 精準佈局、頁面事件擴展三大核心,即可應對發票、報表、合同等主流業務場景。新項目建議直接起步 iText 7 或 OpenPDF,享受現代 API 與長期維護保障。