使用經典 iText 2.1.7 (lowagie) + iTextAsian.jar 生成支援中文、嵌入圖片的 PDF。注意:iText 5+ 版本授權變更 (AGPL),商業專案請確認合規或改用 Apache PDFBox / OpenPDF。
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext-asian</artifactId>
<version>2.1.7</version>
</dependency>
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream("c:/out.pdf"));
document.open();
// 1. 中文字體 (使用亞洲字體包內建 STSong-Light)
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font cnFont = new Font(bf, 12, Font.NORMAL);
document.add(new Paragraph("你好,iText 中文測試!", cnFont));
// 2. 插入圖片 (自動縮放適應頁寬)
Image img = Image.getInstance("c:/photo.jpg");
img.scaleToFit(PageSize.A4.getWidth() - 72, PageSize.A4.getHeight() - 72); // 留邊距
img.setAlignment(Image.ALIGN_CENTER);
document.add(img);
// 3. 表格範例
Table table = new Table(3);
table.setBorderWidth(1);
table.setPadding(5);
table.addCell(new Cell("Header").setHeader(true).setColspan(3));
table.addCell("A1"); table.addCell("B1"); table.addCell("C1");
table.addCell("A2"); table.addCell("B2"); table.addCell("C2");
document.add(table);
document.close();
BaseFont.NOT_EMBEDDED 不嵌入字體檔,依賴閱讀器系統字體,**PDF 體積小但跨平台顯示風險較大**;生產環境建議 BaseFont.EMBEDDED 並授權字體。Image.scaleAbsolute(w,h) 強制尺寸;scalePercent(50) 百分比縮放;scaleToFit(maxW, maxH) 等比縮放至邊界內 (推薦)。Table/Cell 為舊版 API,iText 5+ 改用 PdfPTable/PdfPCell,功能更強。com.openhtmltopdf:openhtmltopdf-pdfbox) — 免費商用。