本文通过一个简单的PDF文件生成例子,期望可以起到抛砖引玉的作用! :)
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class TestPdf {
public static void main(String[] args) {
//创建一个文档对象
Document doc = new Document();
try {
//定义输出位置并把文档对象装入输出对象中
PdfWriter.getInstance(doc, new FileOutputStream("c:/hello.pdf"));
//打开文档对象
doc.open();
// 加入文字“Hello World”
doc.add(new Paragraph("HelloWorld"));
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
// 在上面的代码中设置了中文字体的显示,你只要使用下面的代码就可以包中文加到PDF中了
String title = "我爱喝咖啡";
Paragraph t = new Paragraph(title, FontChinese);
doc.add(t);
Image jpeg = Image.getInstance("C:/girl.jpg");
//图片居中
jpeg.setAlignment(Image.ALIGN_CENTER);
doc.add(jpeg);
Table table = new Table(2);
//设置表格边框
table.setBorderWidth(1);
table.setPadding(5);
table.setBorderColor(new java.awt.Color(0, 0, 255));
table.setBackgroundColor(new java.awt.Color(0, 100, 100));
Cell cel0 = new Cell("Title");
cel0.setHorizontalAlignment(1); //0:left ,1:center ,2:right
cel0.setColspan(2);
cel0.setHeader(true);
table.endHeaders();
Cell cel1 = new Cell("aaaaaaaa");
Cell cel2 = new Cell("bbbbbbb");
cel2.setHorizontalAlignment(1); //0:left ,1:center ,2:right
//分列
Cell cel3 = new Cell("cccccc");
cel3.setColspan(2);
Cell cel4 = new Cell("dddd");
Cell cel5 = new Cell(t);
table.addCell(cel0);
table.addCell(cel1);
table.addCell(cel2);
table.addCell(cel3);
table.addCell(cel4);
table.addCell("");
table.addCell("");
table.addCell(cel5);
doc.add(table);
doc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (DocumentException e) {
e.printStackTrace();
}
catch (Exception e) {}
}
}