首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 生成 PDF 實戰:基於 iText 打造專業表格報表與水印

     編輯:Java 相關知識

iText (現 Lowagie/iText 7) 是 Java 平台生成/操作 PDF 的經典庫。本例展示如何建立 A4 頁面、設定中文字體、添加水印、頁首頁尾、構建複雜表格 (合併儲存格、樣式、顏色、對齊),輸出專業級報表檔案。

核心步驟解析

1. 文檔初始化與中文字體

Document document = new Document(PageSize.A4, 50, 50, 100, 50); // 頁面大小、邊距
PdfWriter.getInstance(document, new FileOutputStream("tables.pdf"));

// 關鍵:註冊中文字體 (需 iTextAsian.jar 或字體檔)
BaseFont bfSong = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
Font fontSong = new Font(bfSong, 10, Font.NORMAL);
Font fontBold = new Font(bfSong, 10, Font.BOLD, new Color(0,0,255));

注意:iText 5/7 字體載入方式不同,新版建議用 FontProgramFactory.createFont() + PdfFontFactory.createFont()。

2. 頁首/頁尾/水印


// 水印
Watermark watermark = new Watermark(Image.getInstance("test.jpg"), x, y);
watermark.scalePercent(50);
document.add(watermark);

// 頁首
HeaderFooter header = new HeaderFooter(new Phrase("Java實例一百例", fontSong), false);
header.setBorder(2); header.setAlignment(Element.ALIGN_RIGHT);
document.setHeader(header);

// 頁尾 (含頁碼佔位)
HeaderFooter footer = new HeaderFooter(new Phrase("第 ", fontSong), new Phrase(" 頁", fontSong));
footer.setAlignment(Element.ALIGN_CENTER); footer.setBorder(1);
document.setFooter(footer);

3. 表格構建核心邏輯

Table table = new Table(4); // 4 欄
table.setDefaultVerticalAlignment(Element.ALIGN_MIDDLE);
table.setBorder(Rectangle.NO_BORDER);
table.setWidths(new int[]{10, 20, 10, 20}); // 相對寬度比例
table.setWidth(100); // 佔頁面寬度 100%

// 表頭跨列
Cell cellmain = new Cell(new Phrase("用戶信息", fontBold));
cellmain.setHorizontalAlignment(Element.ALIGN_CENTER);
cellmain.setColspan(4); // 合併 4 列
cellmain.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
table.addCell(cellmain);

// 分組表頭
Cell cellleft = new Cell(new Phrase("收貨人信息", fontItalic)); cellleft.setColspan(2); table.addCell(cellleft);
Cell cellright = new Cell(new Phrase("訂貨人信息", fontItalic)); cellright.setColspan(2); table.addCell(cellright);

// 資料列
table.addCell(new Phrase("姓名", fontSong));
table.addCell(new Phrase("張三", fontSong));
table.addCell(new Phrase("姓名", fontSong));
table.addCell(new Phrase("李四", fontSong));
// ... 後續欄位同理

document.add(table);
document.close(); // 必須關閉才會真正寫入檔案

iText 版本遷移指南 (5.x → 7.x/8.x)

功能iText 5 (舊)iText 7/8 (新)
核心類Document, PdfWriter, Table, CellDocument, PdfWriter, Table, Cell (包路徑變更 com.itextpdf.layout)
字體BaseFont, FontPdfFont, FontProgram
表格Table, Cell (舊)Table, Cell (新 API: addCell() 返回 Table, 支援鏈式)
水印WatermarkCanvas + 事件處理器 IEventHandler
頁首尾HeaderFooterIEventHandler 實作 handleEvent()

生產級建議

  • 授權合規:iText 5/7 核心版為 AGPL,商業閉源專案需購買商業授權或改用 Apache PDFBox (Apache 2.0) / OpenPDF (LGPL/MPL,iText 4 分支)。
  • 大報表串流輸出:避免一次性載入大量資料到記憶體,使用 PdfPTable (iText 5) 或 Table (iText 7) 的 setComplete(false) 分頁寫入。
  • 模板引擎:複雜報表建議用 JasperReports (JRXML 模板) 或 Thymeleaf + Flying Saucer (xhtml2pdf) 分離業務與排版。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved