您的位置:首页 > 编程语言 > Java开发

滴水穿石--Java 生成PDF文件--iText使用之插入图片和中文乱码

2012-12-16 14:55 1066 查看
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();
}
}


运行效果图:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: