itextpdf使用document操作文本可以使用3個對象來做:Chunk、Phrase、Paragraph。
itextpdf5的包對它們的介紹是這樣的:
chunk:
這是可以添加到文檔中最小的重要部分。
大多數元素可以划分為一個或多個塊。chunkis是一個帶有特定字體的字符串。所有其他布局參數都應該在這個textis塊添加到的對象中定義。
Phrase:
短語是一系列的塊。
一個短語有一個主字體,但是短語中的一些塊可以有不同於主字體的字體。一個短語中的所有塊都有相同的開頭。
Paragraph:
A Paragraph is a series of Chunks and/or Phrases.
A Paragraph has the same qualities of a Phrase, but alsosome additional layout-parameters:
•the indentation
•the alignment of the text
它們有一些自己的特點:
在繼承結構上,paragraph繼承了phrase。phrase和paragraph的文本會自動換行,而chunk是不會自動換行的,超出頁面的部分不會被顯示。
所以,chunk可以設置文本本身的一些屬性,如文字背景,下划線,行高。
而paragraph可以操作文字的排版,段落的間距,行間距,等等。phrase功能跟單一,能設置行間距,也被paragraph繼承了。
1、Paragraph的一些方法的功能:
代碼:
Paragraph paragraph = new Paragraph(text,firstCoverFont); /** 設置行間距,倆個參數:float fixedLeading, float multipliedLeading, * 總的行間距可以用getTotalLeading()來查看, 可以理解是兩行文字,頂部到頂部的距離,如果是0,兩行文字是重疊的。 * 計算方式:fixedLeading+multipliedLeading*fontSize。在pdfDocument中是當前字體;在ColumnText,是指最大字體。 * 其中fixedLeading是固定參數,默認值是:1.5倍的fontsize * multipliedLeading是可變參數,默認值是0. */ paragraph.setLeading(10,2);//設置行間距 paragraph.setAlignment(Element.ALIGN_CENTER);//設置對齊方式:居中、左對齊、右對齊 paragraph.setFirstLineIndent(20f);//設置首行縮進 paragraph.setExtraParagraphSpace(200f);//設置段落之間的空白,測試無效,可以沒找到正確的書寫格式 paragraph.setIndentationLeft(10f);//設置段落整體的左縮進 paragraph.setIndentationRight(20f);//設置段落整體的右縮進 paragraph.setPaddingTop(10f);//設置距離上一元素的頂部padding paragraph.setSpacingAfter(10f);//設置段落下方的空白距離 paragraph.setSpacingBefore(10f);//設置段落上方的留白,,如果的本頁的第一個段落,該設置無效 doc.add(paragraph);
2、chunk的方法
Chunk chunk = new Chunk("測試chunk",firstCoverFont); chunk.setBackground(BaseColor.GREEN);//文字背景色 chunk.setLineHeight(10);//行高 chunk.setUnderline(2, 3);//下划線,或者文字任意文字的線條 doc.add(chunk);
3、將文本放置的任意大小,頁面任意位置
官方文檔:
String path = "E:/demo/pdfCreat/"+System.currentTimeMillis()+".pdf";//輸出pdf的路徑 Document doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(path)); doc.open(); String text = readfile("src/main/resources/file/pdf/test.text"); Rectangle rect = new Rectangle(300, 300, 400, 400);//文本框位置 rect.setBorder(Rectangle.LEFT);//顯示邊框,默認不顯示,常量值:LEFT, RIGHT, TOP, BOTTOM,BOX, rect.setBorderWidth(1f);//邊框線條粗細 rect.setBorderColor(BaseColor.GREEN);//邊框顏色 PdfContentByte cb = writer.getDirectContent(); cb.rectangle(rect); ColumnText ct = new ColumnText(cb); ct.addText(new Phrase("test",firstCoverFont)); ct.setSimpleColumn(rect); ct.setUseAscender(false); ct.go();
簡單方式:
Rectangle rect = new Rectangle(300, 300, 400, 400);//文本框位置 rect.setBorder(Rectangle.LEFT);//顯示邊框,默認不顯示,常量值:LEFT, RIGHT, TOP, BOTTOM,BOX, rect.setBorderWidth(1f);//邊框線條粗細 rect.setBorderColor(BaseColor.GREEN);//邊框顏色 ColumnText cts = new ColumnText(writer.getDirectContent()); cts.addText(new Phrase("test",firstCoverFont)); cts.setSimpleColumn(rect); cts.go();
