IText是開源的,對與打印PDF做的還不錯,下邊一個例子關(guān)于IText的,列出了大部份常用的功能。
import java.io.FileOutputStream;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;



public class Example
{
private static Font FONT_11;
private static BaseFont msgothic;

public static void main(String[] args) throws Exception
{

try
{
//定義字體
msgothic = BaseFont.createFont("D:\\workspace\\UseIText\\MSMINCHO.TTC,0",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
FONT_11=new Font(msgothic);
FONT_11.setSize(11);

}catch(Exception e)
{
e.printStackTrace();
}
//為了測試方便,加入自動關(guān)閉打開acrord32
Runtime.getRuntime().exec("tskill acrord32").waitFor();
Thread.sleep(1000);
Document document=new Document(PageSize.A4.rotate());
//寫文件
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream("d:/temp.pdf"));
document.open();
makeDocument(document);
document.close();
//為了測試方便,加入自動關(guān)閉打開acrord32
Runtime.getRuntime().exec("\"c:\\Program Files\\Adobe\\Acrobat 7.0\\Reader\\acrord32.exe\" d:/temp.pdf").waitFor();
}

public static void makeDocument(Document document)throws Exception
{
//table大部份操做類似與html,下邊是一些常用的參數(shù)
//3是總的列數(shù),也可以同時指定行數(shù)和列數(shù)new Table(3,4)
Table table=new Table(3);
//table的寬度
table.setWidth(98);
//類似html的cellSpaceing
table.setSpacing(2);
//每一列的寬度,是比例不是固定寬度

table.setWidths(new int[]
{10,30,60});
//對齊方式
table.setAlignment("CENTER");
//table是否有邊框
table.setBorder(0);
//cell默認(rèn)是否有邊框
table.setDefaultCellBorder(0);
//自動填充空白
table.setAutoFillEmptyCells(true);
int n=10;

for(int i=0;i<n;i++)
{
makeContent(table);
}
//新的一頁要加上這句
document.newPage();

for(int i=0;i<n;i++)
{
makeContent(table);
}
document.add(table);
}

public static void makeContent(Table table)throws Exception
{
int len = table.columns();

for(int i=0;i<len;i++)
{
String testStr = "test"+i+"xxxxxxxxxxxxxxxxxxxxxx";
Cell cell=new Cell(testStr);
//max lines ,設(shè)置成1防止換行,配合cell寬度,可以實(shí)現(xiàn)自動截取
cell.setMaxLines(1);
table.addCell(cell);
}
}
//構(gòu)造一個自定義的cell

public static Cell makeCell(int colspan,String align,int maxLines,Font font)
{
Cell cell = null;
Paragraph paragraph =null;

try
{
//使用自定義字體
paragraph=new Paragraph("testxxx",font);
cell=new Cell(paragraph);
//設(shè)置colspan,同樣的方法可以設(shè)置rowspan

if(colspan >1)
{
cell.setColspan(colspan);
}
//設(shè)置對齊

if((align != null) && (!align.equals("")))
{
cell.setHorizontalAlignment(align);
}
//設(shè)置maxlines
cell.setMaxLines(maxLines);

}catch(Exception e)
{
e.printStackTrace();
}
return cell;
}
}
