残雪余香

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

iText默认是不支持中文的,处理中文需要用到itext-asian.jar包,关键代码:

处理中文:

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);    
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
添加图片:
Image image = Image.getInstance("http://a.fsdn.com/con/icons/it/itext@sf.net/logo_itext.gif"); 
完成实例代码:
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
public class TestPdf { 
    public static void main(String[] args) throws Exception{
        //step1  
        Document document = new Document();  
        //step2  
        PdfWriter.getInstance(document, new FileOutputStream("first.pdf"));  
        //step3  
        document.open();  
        //step4  
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);      
        Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);  
        Paragraph p = new Paragraph("Hello World,this is my first pdf!这是我的第一个pdf实例",fontChinese);
        document.add(p);  
        //添加一个图片  
        Image image = Image.getInstance("http://a.fsdn.com/con/icons/it/itext@sf.net/logo_itext.gif");  
        document.add(image);  
        //step5 
        document.close();   
    }
} 
运行效果图:

posted on 2012-12-16 14:55  残雪余香  阅读(2097)  评论(0编辑  收藏  举报