銀行對帳單、電子書章節等場景需動態生成 PDF。本文使用免費強大的 iText Java 庫(支援 HTML、RTF、XML、PDF 多格式、多字體、水印、加密),構建完整範例應用。
| 類別 | 用途 |
| com.itextpdf.text.Document | PDF 文件容器,首個實例化 |
| com.itextpdf.text.pdf.PdfWriter | PDF 編寫器,決定輸出類型 |
| Paragraph | 縮進段落 |
| Chapter / Section | 章節結構,Chapter 自動換頁編號 |
| Font | 字體規范(字體集、大小、樣式、顏色) |
| List / ListItem | 列表與列表項 |
| PdfPTable / PdfPCell | 表格與儲存格(支援跨行跨列) |
| Anchor | 文內連結或外部連結 |
| Image | 圖片(支援多種縮放模式) |
範例應用逐步建構
1. 建立文件與編寫器
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("C:\\ITextTest.pdf"));
document.open();
2. 基本文字與錨點目標
Anchor anchorTarget = new Anchor("First page of the document.");
anchorTarget.setName("BackToTop");
Paragraph p1 = new Paragraph();
p1.setSpacingBefore(50);
p1.add(anchorTarget);
document.add(p1);
document.add(new Paragraph("Different color/font text.",
FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0,255,0,0))));
3. 章節結構
Paragraph title1 = new Paragraph("Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new CMYKColor(0,255,255,17)));
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0); // 不顯示章號
Paragraph title11 = new Paragraph("Section 1 in Chapter 1", ...);
Section section1 = chapter1.addSection(title11);
section1.add(new Paragraph("Section content..."));
4. 表格建立
PdfPTable table = new PdfPTable(3); // 3 欄
table.setSpacingBefore(25);
table.setSpacingAfter(25);
table.addCell(new PdfPCell(new Phrase("Header1")));
table.addCell(new PdfPCell(new Phrase("Header2")));
table.addCell(new PdfPCell(new Phrase("Header3")));
table.addCell("1.1"); table.addCell("1.2"); table.addCell("1.3");
section1.add(table);
5. 列表
List list = new List(true, false, 10); // 編號、非字母、縮進 10
list.add(new ListItem("First item"));
list.add(new ListItem("Second item"));
section1.add(list);
6. 圖片
Image img = Image.getInstance("IBMLogo.bmp");
img.scaleAbsolute(120f, 120f); // 固定尺寸
section1.add(img);
7. 文內連結(回到頂部)
Paragraph title2 = new Paragraph("Using Anchor", ...);
title2.setSpacingBefore(5000);
Anchor anchor2 = new Anchor("Back To Top");
anchor2.setReference("#BackToTop");
section1.add(title2);
section1.add(anchor2);
8. 完成文件
document.add(chapter1);
document.close();
執行與輸出
- 下載範例
j-itextsample.jar 解壓
- 設定 classpath 含
itext-5.3.0.jar
- 執行
java com.itext.test.ITextTest
- 產生
C:\ITextTest.pdf,含首頁文字、章節、表格、列表、圖片、文內連結
進階特性與優勢
- 同一元素語法支援多種 Writer:HtmlWriter、RtfWriter、XmlWriter 等
- 輸出流重導向靈活:主控台、Servlet 輸出流、任意 OutputStream
- 水印、加密、細節控制:完整 PDF 功能支援
結語
iText 以統一 API 支援多格式輸出,是 Java 動態生成文件的首選庫。掌握 Document、Writer、基本元素(段落、章節、表格、列表、圖片、錨點)即可構建專業級 PDF 產生器。
- 上一篇文章: 解決 java.lang.OutOfMemoryError: allocLargeArray 記憶體溢位完整指南
- 下一篇文章: Java 下一代語言共同特性(一):操作符重載在 Groovy、Scala、Clojure 中的實現差異
Copyright ©
程式碼之家 All Rights Reserved