`
weichen
  • 浏览: 3172 次
  • 性别: Icon_minigender_1
  • 来自: 天津
文章分类
社区版块
存档分类
最新评论

iText生成pdf文件基本使用

阅读更多
使用的版本是目前最新的5.0.3,可以在http://itextpdf.com/index.php下载,中文语言包下的可能不是最新的,导致调试出了问题,最后用了个笨方法解决的。
//1.建立Document实例
Document document = new Document();
//2.建立一个书写器与Document对象关联,通过书写器将文档写入磁盘
PdfWriter.getInstance(document, new FileOutputStream("f:/test.pdf"));
//3.打开文档
document.open();
//4.向文档中添加内容
	//a)添加一个图片
	Image img = Image.getInstance("f:/pdf.jpg");
	img.setAlignment(Image.LEFT|Image.TEXTWRAP);
	img.scalePercent(30f);
	//document.add(img);
	//b)添加一个段落
	document.add(new Paragraph("iText HelloWorld"));
	//c)添加一个块
	document.add(new Chunk("Text is underline", FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12, Font.UNDERLINE)));
	//d)添加中文,需要引入iTextAsian.jar
	BaseFont bfChi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
	Font fontChi = new Font(bfChi, 12, Font.NORMAL);
	document.add(new Paragraph("中文测试", fontChi));
	//e)添加一个表格
	//表格内部格式和html中的格式差不多
	PdfPTable table = new PdfPTable(4);
	table.setWidthPercentage(100);   
	table.setWidthPercentage(100);   
	table.addCell (new Paragraph ("学号",fontChi));   
	PdfPCell cell = new PdfPCell (new Paragraph ("00000001",fontChi));   
	cell.setColspan (3);   
	table.addCell (cell);   
	table.addCell (new Paragraph ("姓名",fontChi));   
	table.addCell (new Paragraph ("张三",fontChi));   
	table.addCell (new Paragraph ("总成绩",fontChi));   
	table.addCell (new Paragraph ("160",fontChi));
	
	table.addCell (new Paragraph ("学号",fontChi));   
	PdfPCell cell2 = new PdfPCell (new Paragraph ("00000002",fontChi));   
	cell2.setColspan (3);   
	table.addCell (cell2); 
	table.addCell (new Paragraph ("姓名",fontChi));   
	table.addCell (new Paragraph ("李四",fontChi));   
	table.addCell (new Paragraph ("总成绩",fontChi));   
	table.addCell (new Paragraph ("167", fontChi)); 
	document.add(table);
//5.关闭文档
document.close();

注释已经很详细了,说一下中文包的问题,按照正常的流程走下来,会报:Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.我理解的大概是语言包没找到吧。因为iText5.X之前,引用iTextAsian.jar中的语言包是在com/lowagie/text/pdf/fonts,而现在是从com/itextpdf/text/pdf/fonts加载的,但是我又不知道最新的包在哪下,所以直接在包中将lowagie改成itextpdf,运行OK。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics