官网下载jar后,解压:
itextpdf-5.3.2.jar
单使用itextpdf-5.3.2.jar
包进行pdf操作是无法进行中文处理的
需要另外下载一个jar包:iTextAsian.jar
创建一个中文转换类:
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
public class PDFParagraph extends Paragraph{
private static final long serialVersionUID = -3007718914459085396L;
public PDFParagraph(String content) {
super(content, getChineseFont());
}
private static final Font getChineseFont()
{
Font fontChinese = null;
try
{
BaseFont baseFont = BaseFont.createFont("C:\\WINDOWS\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H , BaseFont.EMBEDDED);
fontChinese = new Font(baseFont, 12,Font.NORMAL);
}
catch (DocumentException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fontChinese;
}
}
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
public class PDFServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PDFParagraph chinese = new PDFParagraph("您好啊!");
Document doc = new Document(PageSize.A4); //建立一个文档对象
try {
//建立一个书写器
PdfWriter.getInstance(doc,new FileOutputStream("F:\\test2.pdf"));
//打开文档
doc.open();
//向文档中添加内容
doc.add(chinese);
//关闭文档
doc.close();
} catch (DocumentException e) {
e.printStackTrace();
}
request.getRequestDispatcher("ok.jsp").forward(request, response);
}
}
[b]当方法运行到POST方法中时,将产生一个异常,
解决方案:
iText5.x版本以上中的font和encoding文件
都是从String RESOURCE_PATH = "com/itextpdf/text/pdf/fonts/" 加载
而老itextasian.jar包名是com.lowagie.text.pdf.fonts
包名不一致导致路径错误
所以需要修改jar包文件夹的命名改为:
com/itextpdf/text/pdf/fonts/ 目录结构
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
如采用自带字库,将产生异常:
"Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized"
处理方式可以采用windos本地字库:
BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
这里要注意一点,C:\\WINDOWS\\Fonts\\simhei.ttf
在指定字库时,要确保该字体存在,在WINDOWS下面这个是默认路径
其他系统自行参考,可以双击字体文件查看标题名,也就是它的字体名称
如仍然使用英文字体,将依旧不能处理中文,此例采用的是simhei.ttf(黑体)[/b]