iText簡介
iText是一個開放源碼的Java類庫,可以用來方便地生成PDF文件。大家通過訪問http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948下載最新版本的類庫,下載完成之后會得到一個.jar包,把這個包加入JDK的classpath即可使用。如果生成的PDF文件中需要出現(xiàn)中文、日文、韓文字符,則還需要通過訪問http://itext.sourceforge.net/downloads/iTextAsian.jar下載iTextAsian.jar包。
關(guān)于iText類庫的使用,http://www.lowagie.com/iText/tutorial/index.html有比較詳細(xì)的教程。該教程從入門開始,比較系統(tǒng)地介紹了在PDF文件中放入文字、圖片、表格等的方法和技巧。讀完這片教程,大致就可以做一些從簡單到復(fù)雜的PDF文件了。不過,試圖通過教程解決在生成PDF文件過程中遇到的所有困難無疑是一種奢望。所以,閱讀iText的api文檔顯得非常重要。讀者在下載類庫的同時,也可以下載類庫的文檔。
可參考資料 :
http://dev.csdn.net/article/62/62119.shtm http://myowndream.blog.com.cn/archives/2007/2089386.shtml
http://tag.csdn.net/tag/itext.xml
一 HelloWorld實例
以下是上述教程中一個最簡單的例子,這個例子刻畫了通過iText生成PDF文件的一般程序框架。讀者只需要在document.open();和document.close();兩條語句中間加入自己希望放在PDF文件中的內(nèi)容即可。該例子只在PDF文件中加了“Hello World“一行文字。
Document document = new Document();
try{
PdfWriter.getInstance(document, new FileOutputStream ("Chap0101.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
}catch(DocumentException de){
System.err.println(de.getMessage());
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
document.close();
可以看到一個PDF文件的輸出,總共只需要5個步驟
a.創(chuàng)建一個Document實例
Document document = new Document();
b.將Document實例和文件輸出流用PdfWriter類綁定在一起
PdfWriter.getInstance(document,new FileOutputStream("HelloWorld.pdf"));
c.打開文檔
document.open();
d.在文檔中添加文字
document.add(new Paragraph("Hello World"));
e.關(guān)閉文檔
document.close();
這樣5個步驟,就可以生成一個PDF文檔了。
然而在PDF中指定文字、圖畫、表格的位置是一件非常麻煩的事情。除了不斷地在程序中修改位置、然后運行程序、生成PDF文件、觀察元素在PDF中的位置是否合理這樣的過程以外,似乎還沒有其它更好的方法。
二。如何使用jsp、servlet輸出iText生成的pdf?
如果每次都在服務(wù)端生成一個PDF文件給用戶,不僅麻煩,而且浪費服務(wù)器資源,最好的方法就是以二進制流的形式輸送到客戶端。
1)JSP輸出:
<%@ page import="java.io.*,java.awt.Color,com.lowagie.text.*,com.lowagie.text.pdf.*"%>
<%
response.setContentType( "application/pdf" );
Document document = new Document();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
PdfWriter writer=PdfWriter.getInstance( document, buffer );
document.open();
document.add(new Paragraph("Hello World"));
document.close();
DataOutput output = new DataOutputStream( response.getOutputStream() );
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for( int i = 0; i < bytes.length; i++ ){
output.writeByte( bytes[i] );
}
%>
2)servlet輸出,稍微改造下就可以使用在struts中:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException{
Document document = new Document(PageSize.A4, 36,36,36,36);
ByteArrayOutputStream ba = new ByteArrayOutputStream();
try{
PdfWriter writer = PdfWriter.getInstance(document, ba);
document.open();
document.add(new Paragraph("Hello World"));
}catch(DocumentException de){
de.printStackTrace();
System.err.println("A Document error:" +de.getMessage());
}
document.close();
response.setContentType("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();
}
三。如何輸出中文?
首先需要下載iTextAsian.jar包,可以到iText的主站上下,ireport也是需要這個包的。然后定義中文字體:
private static final Font getChineseFont() {
Font FontChinese = null;
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
FontChinese = new Font(bfChinese, 12, Font.NORMAL);
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return FontChinese;
}
我將產(chǎn)生中文字體封裝在方法內(nèi),自定義一個段落PDFParagraph繼承自Paragraph,默認(rèn)使用中文字體:
class PDFParagraph extends Paragraph {
public PDFParagraph(String content) {
super(content, getChineseFont());
}
}
使用的時候就可以簡化了:
Paragraph par = new PDFParagraph("你好");
四。如何設(shè)置PDF橫向顯示和打印?
Rectangle rectPageSize = new Rectangle(PageSize.A4);// 定義A4頁面大小
rectPageSize = rectPageSize.rotate();// 加上這句可以實現(xiàn)A4頁面的橫置
Document doc = new Document(rectPageSize,50,50,50,50);//4個參數(shù),設(shè)置了頁面的4個邊距
五。如何設(shè)置跨行和跨列?
使用PdfPTable和PdfPCell 是沒辦法實現(xiàn)跨行的,只能跨列,要跨行使用com.lowagie.text.Table和com.lowagie.text.Cell類,Cell類有兩個方法:setRowspan()和setColspan()。
六。如何設(shè)置單元格邊界寬度?
Cell類的系列setBorderWidthXXXX()方法,比如setBorderWidthTop(),setBorderWidthRight()等
七。如何設(shè)置表頭?
希望每一頁都有表頭,可以通過設(shè)置表頭來實現(xiàn)。對于PdfPTable類來說,可以這樣設(shè)置:
PdfPTable table = new PdfPTable(3);
table.setHeaderRows(2); // 設(shè)置了頭兩行為表格頭
而對于om.lowagie.text.Table類,需要在添加完所有表頭的單元格后加上一句代碼:
table.endHeaders();
八。如何設(shè)置列寬?
Table table = new Table(8);
float[] widths = { 0.10f, 0.15f, 0.21f, 0.22f, 0.08f, 0.08f, 0.10f,
0.06f };
table.setWidths(widths);
上面的代碼設(shè)置了一個有8列的表格,通過一個float數(shù)組設(shè)置列寬,這里是百分比。
九。單元格內(nèi)段落文字居中和換行?
居中通過Cell類來設(shè)置,一開始我以為設(shè)置段落對齊就可以了,沒想到是需要設(shè)置單元格:
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
轉(zhuǎn)義符\n實現(xiàn)。在我的這個應(yīng)用中,因為數(shù)據(jù)庫取出的數(shù)據(jù)是為了顯示在html上的,所以有很多<br>標(biāo)簽,可以使用正則表達(dá)式替換成"\n"
"<br>1.測試<br>2.測試2".replaceAll("<br>|</br>","\n");
十。如何顯示頁碼?
復(fù)雜的頁碼顯示和水印添加,需要使用到PdfPageEventHelper、PdfTemplate等輔助類,具體的例子參見iText的文檔,如果只是為了簡單的顯示頁數(shù),可以使用下面的代碼:
HeaderFooter footer = new HeaderFooter(new Phrase("頁碼:",getChineseFont()), true);
footer.setBorder(Rectangle.NO_BORDER);
document.setFooter(footer);
document.open();
你可能注意到了,添加footer需要在document.open之前。