1. 准备jar
(1)、我用的是iText-2.1.7.jar、iTextAsian.jar,注意:iText-5.0以上需要下载最新的iTextAsian.jar。
(2)、
public static void createPDF() {
File file = new File("D:\\学生信息.pdf");
BaseFont bfChinese = null;// 定义字体样式对象
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);// 定义中文字体样式
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Font font = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小
Document document = new Document();
document.setPageSize(PageSize.A4);
PdfPTable table = new PdfPTable(2);
table.getDefaultCell().setBorder(1);
PdfPCell cell1 = new PdfPCell();
PdfPCell cell2 = new PdfPCell();
PdfPCell cell3 = new PdfPCell();
PdfPCell cell4 = new PdfPCell();
PdfPCell cell5 = new PdfPCell();
cell1.setColspan(2);// 合并2列
cell1.setBorder(0);
cell1.setPaddingTop(15.0f);
cell1.setPaddingBottom(8.0f);
cell1.setPhrase(new Phrase("学生信息列表:", font));
cell2.setPhrase(new Phrase("姓名", font));
cell3.setPhrase(new Phrase("年龄", font));
cell4.setPhrase(new Phrase("张三", font));
cell5.setPhrase(new Phrase("23", font));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
try {
document.add(table);
} catch (DocumentException e) {
e.printStackTrace();
}
document.close();
System.out.println("导出pdf成功..");
}
public static void main(String[] args) {
<span style="white-space:pre"> </span>createPDF();
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}