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

iText PDF 庫實戰指南:文檔創建、內容添加、表格、圖片、水印、書簽、頁眉頁腳、HTML 轉 PDF 等

     編輯:Java 綜合教學

iText PDF 庫實戰指南(基於 iText 5.2.1)

iText 是著名的開源 Java 庫,用於生成、操作 PDF 文檔,支持 XML/HTML 轉 PDF、加密、簽名、表單等高級功能。官網:itextpdf.com

1. 基礎文檔創建與屬性設置

Rectangle rect = new Rectangle(PageSize.B5.rotate());
rect.setBackgroundColor(BaseColor.ORANGE);
Document doc = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(doc, out);
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
// 設置加密
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
    PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
// 文檔元數據
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");
doc.setMargins(10, 20, 30, 40);
doc.open();
doc.add(new Paragraph("Hello World"));
doc.close();

基礎文檔

2. 多頁面控制

document.add(new Paragraph("First page"));
document.add(new Paragraph(Document.getVersion()));
document.newPage();
writer.setPageEmpty(false);
document.newPage();
document.add(new Paragraph("New page"));

多頁面

3. 頁面刪除、插入、排序

PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf");
reader.selectPages("1,3"); // 僅保留頁 1,3
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "deletePage2.pdf"));
stamp.insertPage(2, reader.getPageSize(1)); // 插入頁面
stamp.close(); reader.close();
// 排序
PdfWriter writer = PdfWriter.getInstance(doc, out);
writer.setLinearPageMode();
writer.reorderPages(new int[]{4,3,2,1});

頁面操作

4. 文本內容元素:Chunk、Phrase、Paragraph、List、Anchor

// Chunk: 最小文本單位
document.add(new Chunk("China"));
Chunk id = new Chunk("chinese", new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.setTextRise(6);
document.add(id);
// Phrase: 帶行距的 Chunk 序列
Phrase director = new Phrase();
director.add(new Chunk("China")); director.add(new Chunk(","));
director.setLeading(24);
// Paragraph: 帶換行屬性的 Phrase
Paragraph info = new Paragraph();
info.add(new Chunk("China ")); info.add(new Chunk("chinese"));
info.add(Chunk.NEWLINE);
// List: 有序/無序列表,支持嵌套
List list = new List(List.ORDERED);
for (int i=0; i<10; i++) {
    ListItem item = new ListItem(String.format("%s: %d movies","country"+(i+1), (i+1)*100));
    List movielist = new List(List.ORDERED, List.ALPHABETICAL);
    // ... 嵌套構建
    item.add(movielist);
    list.add(item);
}
document.add(list);
// Anchor: 內部/外部鏈接
Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
dest.setName("CN"); dest.setReference("https://www.china.com"); // 外部
document.add(dest);
Anchor toUS = new Anchor("Go to first page.", font);
toUS.setReference("#CN"); // 內部跳轉

文本元素

5. 圖片處理

Image img = Image.getInstance("resource/test.jpg");
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(1000, 72);
img.setRotationDegrees(-30);
document.add(img);

圖片

6. 章節與書簽(目錄)

Paragraph title = new Paragraph("Title");
Chapter chapter = new Chapter(title, 1);
Section section = chapter.addSection(new Paragraph("Section A"));
section.setBookmarkTitle("bmk");
section.setIndentation(30);
Section subsection = section.addSection(new Paragraph("Sub Section A"));
document.add(chapter);

書簽

7. 段落格式設置

Paragraph p = new Paragraph("段落內容");
p.setAlignment(Element.ALIGN_JUSTIFIED);
p.setIndentationLeft(15f);
p.setIndentationRight(60f);
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);

段落設置

8. 表格

// 基礎表格
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3); table.addCell(cell);
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2); table.addCell(cell);
table.addCell("row 1; cell 1"); table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1"); table.addCell("row 2; cell 2");
document.add(table);
// 嵌套表格
PdfPTable nested1 = new PdfPTable(2); nested1.addCell("1.1"); nested1.addCell("1.2");
PdfPTable nested2 = new PdfPTable(1); nested2.addCell("2.1"); nested2.addCell("2.2");
table.addCell(nested1); table.addCell(nested2);
// 表格寬度設置
float[] widths = {40f, 40f, 20f, 80f};
table.setWidths(widths);
table.setWidthPercentage(50, new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72)));

表格

9. 單元格細節控制

PdfPCell cell = new PdfPCell(new Paragraph("blah blah"));
cell.setNoWrap(false); // 自動換行
cell.setFixedHeight(50f);
cell.setMinimumHeight(50f);
cell.setUseBorderPadding(true);
cell.setPadding(10f);
cell.setBorder(Rectangle.BOTTOM);
cell.setBorderColorBottom(BaseColor.MAGENTA);
cell.setBorderWidthBottom(5f);
cell.setBackgroundColor(BaseColor.RED);

單元格

10. 繪圖:線條、箭頭、虛線

// 箭頭
document.add(new VerticalPositionMark() {
    public void draw(PdfContentByte canvas, float llx, float lly, float urx, float ury, float y) {
        canvas.beginText();
        BaseFont bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
        canvas.setFontAndSize(bf, 12);
        canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char)220), llx-10, y, 0); // LEFT
        canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char)220), urx+10, y+8, 180); // RIGHT
        canvas.endText();
    }
});
// 直線
Paragraph p1 = new Paragraph("LEFT");
p1.add(new Chunk(new LineSeparator()));
p1.add("R"); document.add(p1);
// 虛線
Paragraph p2 = new Paragraph("LEFT");
p2.add(new Chunk(new DottedLineSeparator()));
p2.add("R"); document.add(p2);
// 下劃線
LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
Paragraph p3 = new Paragraph("NNNN...");
p3.add(UNDERLINE);

繪圖

11. 目錄大綱(Bookmarks)

document.newPage();
document.add(new Chunk("Chapter 1").setLocalDestination("1"));
document.newPage();
document.add(new Chunk("Chapter 2").setLocalDestination("2"));
document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
PdfContentByte cb = writer.getDirectContent();
PdfOutline root = cb.getRootOutline();
PdfOutline o1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");
PdfOutline o2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");
PdfOutline o21 = new PdfOutline(o2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");

大綱

12. 頁眉頁腳

writer.setPageEvent(new PdfPageEventHelper() {
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        cb.setFontAndSize(bf, 10);
        float x = document.top(-20);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "H-Left", document.left(), x, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber()+" page", (document.right()+document.left())/2, x, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "H-Right", document.right(), x, 0);
        float y = document.bottom(-20);
        cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "F-Left", document.left(), y, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, writer.getPageNumber()+" page", (document.right()+document.left())/2, y, 0);
        cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, "F-Right", document.right(), y, 0);
        cb.endText(); cb.restoreState();
    }
});

頁眉頁腳

13. 幻燈片放映模式

writer.setPdfVersion(PdfWriter.VERSION_1_5);
writer.setViewerPreferences(PdfWriter.PageModeFullScreen);
writer.setPageEvent(new PdfPageEventHelper() {
    public void onStartPage(PdfWriter writer, Document document) {
        writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
        writer.setDuration(5);
    }
});

幻燈片

14. 條形碼、水印、自定義字體、HTML 轉 PDF、PDF 拆分合併、壓縮 ZIP

更多高級用法請參考官方文檔與示例代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved