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(); } }
运行效果图: