今天在用itext做导出pdf文件时出现了中文不显示,然后就看itext的api又写了一个PDFExcel让其继承Cell.如下
/**
*
*/
package com.pdf.demo;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Font;
/**
* @author 崔冉 E-mail:cuiran2001@163.com
* @version 创建时间:2009-7-14 下午08:47:53
*/
public class PDFCell extends Cell {
public PDFCell(String content, int rowspan, int colspan)
throws BadElementException {
super(new Chunk(content, PDFChineseFont
.createChineseFont(10, Font.NORMAL)));
setRowspan(rowspan);
setColspan(colspan);
setHeader(false);
}
public PDFCell(String content)
throws BadElementException {
super(new Chunk(content, PDFChineseFont
.createChineseFont(10, Font.NORMAL)));
setHeader(false);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
然后写个例子如下。
/**
*
*/
package com.pdf.demo;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
/**
* @author Administrator
*
*/
public class pdfTa {
/**
* @param args
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] title={"序号","项目名称","计划名称","项目类型","项目密级","开始时间","结束时间"};
Document document=new Document();
BaseFont bfChinese=null;
try {
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL );
Paragraph pragraph=new Paragraph("计划信息", FontChinese);
try {
try {
PdfWriter.getInstance(document, new FileOutputStream("Chap0103.pdf"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.addTitle("这是一个demo!");
document.addSubject("计划信息");
document.addCreator("天外来客");
document.addCreationDate();
document.open();
try {
document.add(pragraph);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Table table=new Table(7);
table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
// table.setPadding(5);
// table.setSpacing(5);
for(int i=0;i<title.length;i++){
table.addCell(new PDFCell(title[i]));
}
try {
document.add(table);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (BadElementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
}
}