一.itext簡介
itext是著名的開放源碼的站點sourceforge一個項目,是用于生成pdf文檔的一個java類庫。通過itext不僅可以生成pdf或rtf的文檔,而且可以将xml、html檔案轉化為pdf檔案。
itext的安裝非常友善,在http://itextpdf.com/ 網站上下載下傳itext.jar檔案後,隻需要在系統的classpath中加入itext.jar的路徑,在程式中就可以使用itext類庫了。
二、建立第一個pdf文檔
用itext生成pdf文檔需要5個步驟:
①建立com.lowagie.text.document對象的執行個體。
document document = new document();
②建立一個書寫器(writer)與document對象關聯,通過書寫器(writer)可以将文檔寫入到磁盤中。
pdfwriter.getinstance(document, new fileoutputstream("helloworld.pdf"));
③打開文檔。
document.open();
④向文檔中添加内容。
document.add(new paragraph("hello world"));
⑤關閉文檔。
document.close();
通過上面的5個步驟,就能産生一個helloworld.pdf的檔案,檔案内容為"hello world"。
建立com.lowagie.text.document對象的執行個體
com.lowagie.text.document對象的建構函數有三個,分别是:
public document();
public document(rectangle pagesize);
public document(rectangle pagesize,
int marginleft,
int marginright,
int margintop,
int marginbottom);
建構函數的參數pagesize是文檔頁面的大小,對于第一個建構函數,頁面的大小為a4,同document(pagesize.a4)的效果一樣;對于第三個建構函數,參數marginleft、marginright、margintop、marginbottom分别為左、右、上、下的頁邊距。
通過參數pagesize可以設定頁面大小、面背景色、以及頁面橫向/縱向等屬性。itext定義了a0-a10、al、letter、halfletter、_11x17、ledger、note、b0-b5、arch_a-arch_e、flsa 和flse等紙張類型,也可以通過rectangle pagesize = new rectangle(144, 720);自定義紙張。通過rectangle方法rotate()可以将頁面設定成橫向。
書寫器(writer)對象
一旦文檔(document)對象建立好之後,需要建立一個或多個書寫器(writer)對象與之關聯。通過書寫器(writer)對象可以将具體文檔存盤成需要的格式,如com.lowagie.text.pdf.pdfwriter可以将文檔存成pdf檔案,com.lowagie.text.html.htmlwriter可以将文檔存成html檔案。
設定文檔屬性
在文檔打開之前,可以設定文檔的标題、主題、作者、關鍵字、裝訂方式、建立者、生産者、建立日期等屬性,調用的方法分别是:
public boolean addtitle(string title)
public boolean addsubject(string subject)
public boolean addkeywords(string keywords)
public boolean addauthor(string author)
public boolean addcreator(string creator)
public boolean addproducer()
public boolean addcreationdate()
public boolean addheader(string name, string content)
其中方法addheader對于pdf文檔無效,addheader僅對html文檔有效,用于添加文檔的頭資訊。
當新的頁面産生之前,可以設定頁面的大小、書簽、腳注(headerfooter)等資訊,調用的方法是:
public boolean setpagesize(rectangle pagesize)
public boolean add(watermark watermark)
public void removewatermark()
public void setheader(headerfooter header)
public void resetheader()
public void setfooter(headerfooter footer)
public void resetfooter()
public void resetpagecount()
public void setpagecount(int pagen)
如果要設定第一頁的頁面屬性,這些方法必須在文檔打開之前調用。
對于pdf文檔,itext還提供了文檔的顯示屬性,通過調用書寫器的setviewerpreferences方法可以控制文檔打開時acrobat reader的顯示屬性,如是否單頁顯示、是否全屏顯示、是否隐藏狀态條等屬性。
另外,itext也提供了對pdf檔案的安全保護,通過書寫器(writer)的setencryption方法,可以設定文檔的使用者密碼、隻讀、可列印等屬性。
添加文檔内容
所有向文檔添加的内容都是以對象為機關的,如phrase、paragraph、table、graphic對象等。比較常用的是段落(paragraph)對象,用于向文檔中添加一段文字。
四、文本處理
itext中用文本塊(chunk)、短語(phrase)和段落(paragraph)處理文本。
文本塊(chunk)是處理文本的最小機關,有一串帶格式(包括字型、顔色、大小)的字元串組成。如以下代碼就是産生一個字型為helvetica、大小為10、帶下劃線的字元串:
chunk chunk1 = new chunk("this text is underlined", fontfactory.getfont(fontfactory.helvetica, 12, font.underline));
短語(phrase)由一個或多個文本塊(chunk)組成,短語(phrase)也可以設定字型,但對于其中以設定過字型的文本塊(chunk)無效。通過短語(phrase)成員函數add可以将一個文本塊(chunk)加到短語(phrase)中,如:phrase6.add(chunk);
段落(paragraph)由一個或多個文本塊(chunk)或短語(phrase)組成,相當于word文檔中的段落概念,同樣可以設定段落的字型大小、顔色等屬性。另外也可以設定段落的首行縮進、對齊方式(左對齊、右對齊、居中對齊)。通過函數setalignment可以設定段落的對齊方式,setalignment的參數1為居中對齊、2為右對齊、3為左對齊,預設為左對齊。
五、表格處理
itext中處理表格的類為:com.lowagie.text.table和com.lowagie.text.pdf.pdfptable,對于比較簡單的表格處理可以用com.lowagie.text.table,但是如果要處理複雜的表格,這就需要com.lowagie.text.pdf.pdfptable進行處理。這裡就類com.lowagie.text.table進行說明。
類com.lowagie.text.table的構造函數有三個:
①table (int columns)
②table(int columns, int rows)
③table(properties attributes)
參數columns、rows、attributes分别為表格的列數、行數、表格屬性。建立表格時必須指定表格的列數,而對于行數可以不用指定。
建立表格之後,可以設定表格的屬性,如:邊框寬度、邊框顔色、襯距(padding space 即單元格之間的間距)大小等屬性。下面通過一個簡單的例子說明如何使用表格,代碼如下:
table table = new table(3);
table.setborderwidth(1);
table.setbordercolor(new color(0, 0, 255));
table.setpadding(5);
table.setspacing(5);
cell cell = new cell("header");
cell.setheader(true);
cell.setcolspan(3);
table.addcell(cell);
table.endheaders();
cell = new cell("example cell with colspan 1 and rowspan 2");
cell.setrowspan(2);
cell.setbordercolor(new color(255, 0, 0));
table.addcell("1.1");
table.addcell("2.1");
table.addcell("1.2");
table.addcell("2.2");
table.addcell("cell test1");
cell = new cell("big cell");
cell.setcolspan(2);
table.addcell("cell test2");
運作結果如下:
header cell test2
代碼1-5行用于建立一個表格,如代碼所示,建立了一個列數為3的表格,并将邊框寬度設為1,顔色為藍色,襯距為5。
代碼6-10行用于設定表格的表頭,第7行cell.setheader(true);是将該單元格作為表頭資訊顯示;第8行cell.setcolspan(3);指定了該單元格占3列;為表格添加表頭資訊時,要注意的是一旦表頭資訊添加完了之後,必須調用endheaders()方法,如第10行,否則當表格跨頁後,表頭資訊不會再顯示。
代碼11-14行是向表格中添加一個寬度占一列,長度占二行的單元格。
往表格中添加單元格(cell)時,按自左向右、從上而下的次序添加。如執行完11行代碼後,表格的右下方出現2行2列的空白,這是再往表格添加單元格時,先填滿這個空白,然後再另起一行,15-24行代碼說明了這種添加順序。
六、圖像處理
itext中處理表格的類為com.lowagie.text.image,目前itext支援的圖像格式有:gif, jpeg, png, wmf等格式,對于不同的圖像格式,itext用同樣的構造函數自動識别圖像格式。通過下面的代碼分别獲得gif、jpg、png圖像的執行個體。
image gif = image.getinstance("vonnegut.gif");
image jpeg = image.getinstance("mykids.jpg");
image png = image.getinstance("hitchcock.png");
圖像的位置
圖像的位置主要是指圖像在文檔中的對齊方式、圖像和文本的位置關系。itext中通過函數public void setalignment(int alignment)進行處理,參數alignment為image.right、image.middle、image.left分别指右對齊、居中、左對齊;當參數alignment為image.textwrap、image.underlying分别指文字繞圖形顯示、圖形作為文字的背景顯示。這兩種參數可以結合以達到預期的效果,如setalignment(image.right|image.textwrap)顯示的效果為圖像右對齊,文字圍繞圖像顯示。
圖像的尺寸和旋轉
如果圖像在文檔中不按原尺寸顯示,可以通過下面的函數進行設定:
public void scaleabsolute(int newwidth, int newheight)
public void scalepercent(int percent)
public void scalepercent(int percentx, int percenty)
函數public void scaleabsolute(int newwidth, int newheight)直接設定顯示尺寸;函數public void scalepercent(int percent)設定顯示比例,如scalepercent(50)表示顯示的大小為原尺寸的50%;而函數scalepercent(int percentx, int percenty)則圖像高寬的顯示比例。
如果圖像需要旋轉一定角度之後在文檔中顯示,可以通過函數public void setrotation(double r)設定,參數r為弧度,如果旋轉角度為30度,則參數r= math.pi / 6。
七、中文處理
預設的itext字型設定不支援中文字型,需要下載下傳遠東字型包itextasian.jar,否則不能往pdf文檔中輸出中文字型。通過下面的代碼就可以在文檔中使用中文了:
basefont bfchinese = basefont.createfont("stsong-light", "unigb-ucs2-h", basefont.not_embedded);
com.lowagie.text.font fontchinese = new com.lowagie.text.font(bfchinese, 12, com.lowagie.text.font.normal);
paragraph pragraph=new paragraph("你好", fontchinese);
八、分頁處理
如果隻是簡單的顯示目前頁碼,使用以下代碼即可(設定了頁面的大小後,會自動分頁)。
1 headerfooter footer = new headerfooter(new phrase("頁碼:",keyfont), true);
2 footer.setborder(rectangle.no_border);
3 document.setheader(footer);
如果要顯示目前頁碼以及總頁碼。
則需要計算總頁數,設定每頁大小,使用pdf.newpage( )手動分頁。
詳見一下代碼:
package com.foster;
import java.io.file;
import java.io.fileoutputstream;
import java.util.arraylist;
import java.util.list;
import com.lowagie.text.cell;
import com.lowagie.text.document;
import com.lowagie.text.documentexception;
import com.lowagie.text.font;
import com.lowagie.text.headerfooter;
import com.lowagie.text.image;
import com.lowagie.text.paragraph;
import com.lowagie.text.table;
import com.lowagie.text.pdf.basefont;
import com.lowagie.text.pdf.pdfpcell;
import com.lowagie.text.pdf.pdfwriter;
public class pdfreport {
public static void main(string[] args) throws exception, documentexception {
list<string> ponum=new arraylist<string>();
add(ponum, 26);
list<string> line=new arraylist<string>();
add(line, 26);
list<string> part=new arraylist<string>();
add(part, 26);
list<string> description=new arraylist<string>();
add(description, 26);
list<string> origin=new arraylist<string>();
add(origin, 26);
//create document instance
document document=new document();
//add chinese font
basefont bfchinese=basefont.createfont("stsong-light", "unigb-ucs2-h", basefont.not_embedded);
//font headfont=new font(bfchinese,10,font.bold);
font keyfont=new font(bfchinese,8,font.bold);
font textfont=new font(bfchinese,8,font.normal);
//create writer associated with document
pdfwriter.getinstance(document, new fileoutputstream(new file("d:\\poreceivereport.pdf")));
document.open();
//seperate page controller
int recordperpage=10;
int fullpagerequired=ponum.size()/recordperpage;
int remainpage=ponum.size()%recordperpage>1?1:0;
int totalpage=fullpagerequired+remainpage;
for(int j=0;j<totalpage;j++){
document.newpage();
//create page number
string pageno=leftpad("頁碼: "+(j+1)+" / "+totalpage,615);
paragraph pagenumber=new paragraph(pageno, keyfont) ;
document.add(pagenumber);
//create title p_w_picpath
image jpeg=image.getinstance("d:\\title.jpg");
jpeg.setalignment(image.align_center);
jpeg.scaleabsolute(530, 37);
document.add(jpeg);
//header information
table theader=new table(2);
float[] widthsheader={2f,3f};
theader.setwidths(widthsheader);
theader.setwidth(100);
theader.getdefaultcell().setborder(pdfpcell.no_border);
string compadd="河源市高新技術開發區興業大道中66号";
string company="豐達音響(河源)有限公司";
string vendor="v006";
string vendorname="中山市盧氏五金有限公司";
string ccn="fhh";
string mas_loc="fhh";
string delivery_note="20130718001";
string receive_date="20130718";
string dept="h11";
string asn="0123456789";
cell c1header=new cell(new paragraph("位址:"+compadd,keyfont));
theader.addcell(c1header);
c1header=new cell(new paragraph("供應商:"+vendor,keyfont));
c1header=new cell(new paragraph("公司:"+company,keyfont));
c1header=new cell(new paragraph("供應商工廠:"+vendorname,keyfont));
c1header = new cell(new paragraph("ccn: "+ccn+" master loc: "+mas_loc,keyfont));
c1header = new cell(new paragraph("送貨編号: "+delivery_note+" 送貨日期: "+receive_date,keyfont));
c1header=new cell(new paragraph("dept:"+dept,keyfont));
c1header=new cell(new paragraph("asn#:"+asn,keyfont));
document.add(theader);
//record header field
table t=new table(5);
float[] widths={1.5f,1f,1f,1.5f,1f};
t.setwidths(widths);
t.setwidth(100);
t.getdefaultcell().setborder(pdfpcell.no_border);
cell c1 = new cell(new paragraph("po#",keyfont));
t.addcell(c1);
c1 = new cell(new paragraph("line",keyfont));
c1 = new cell(new paragraph("part#",keyfont));
c1 = new cell(new paragraph("description",keyfont));
t.addcell(c1);
c1 = new cell(new paragraph("origin",keyfont));
//calculate the real records within a page ,to calculate the last record number of every page
int maxrecordinpage= j+1 ==totalpage ? (remainpage==0?recordperpage:(ponum.size()%recordperpage)):recordperpage;
for(int i=j*recordperpage;i<((j*recordperpage)+maxrecordinpage);i++){
cell c2=new cell(new paragraph(ponum.get(i), textfont));
t.addcell(c2);
c2=new cell(new paragraph(line.get(i), textfont));
c2=new cell(new paragraph(part.get(i), textfont));
c2=new cell(new paragraph(description.get(i), textfont));
c2=new cell(new paragraph(origin.get(i), textfont));
}
document.add(t);
if(j+1==totalpage){
paragraph foot11 = new paragraph("檔案隻作 foster 收貨用"+printblank(150)+"__________________________",keyfont);
document.add(foot11);
paragraph foot12 = new paragraph("printed from foster supplier portal"+printblank(134)+company+printblank(40)+"版本: 1.0",keyfont);
document.add(foot12);
headerfooter footer11=new headerfooter(foot11, true);
footer11.setalignment(headerfooter.align_bottom);
headerfooter footer12=new headerfooter(foot12, true);
footer12.setalignment(headerfooter.align_bottom);
}
document.close();
}
public static string leftpad(string str, int i) {
int addspaceno = i-str.length();
string space = "";
for (int k=0; k<addspaceno; k++){
space= " "+space;
};
string result =space + str ;
return result;
}
public static void add(list<string> list,int num){
for(int i=0;i<num;i++){
list.add("test"+i);
public static string printblank(int tmp){
string space="";
for(int m=0;m<tmp;m++){
space=space+" ";
}
return space;
}
為了使副标題嚴格對齊,使用了表格table進行控制,但是卻沒能找到去掉表格邊框的方法。
九、總結
總的來說,itext是一套java環境下不錯的制作pdf的元件。因為itext支援jsp/javabean下的開發,這使得b/s應用中的報表問題能得到很好的解決。由于itext畢竟不是專門為制作報表設計,所有報表中的内容、格式都需要通過寫代碼實作,相對于那些專業的支援可視化設計的報表軟體來說,程式設計的工作量就有一定程度的增加。
可以使用第三方專業控件進行對pdf,word文檔的操作,例如pageoffice