iText创建PDF文件

项目有生成PDF文件的需求,要求把数据库中的信息绘制成表格、还有一些图片、文档,都整合到一个PDF中提供下载。因此就研究了下iText
代码很简答,不做过多解释,大家一看便懂,附件中附上iText的核心包,和一个中文处理包,以及核心包的源码。

Document doc = new Document (PageSize.A4);
PdfWriter.getInstance (doc, new FileOutputStream ("c:/test/pdf/test.pdf"));
doc.open ();

//标题字体
BaseFont bfTitle = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFont = new Font(bfTitle, 18, Font.NORMAL);

//内容字体
BaseFont bfComic = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font font = new Font(bfComic, 9, Font.NORMAL);

Paragraph titleP=new Paragraph("儿童信息 Child Information\n\n",titleFont);
titleP.setAlignment(titleP.ALIGN_CENTER);
doc.add(titleP);
//生成4列的表格
PdfPTable table = new PdfPTable (4);
table.setWidthPercentage(100);
table.setWidthPercentage(100);
table.addCell (new Paragraph ("Children-id",font));
PdfPCell cell = new PdfPCell (new Paragraph ("09140800002",font));
cell.setColspan (3);
table.addCell (cell);
// 添加第一行
table.addCell (new Paragraph ("Name(CN)",font));
table.addCell (new Paragraph ("党宁生",font));
table.addCell (new Paragraph ("Name(EN)",font));
table.addCell (new Paragraph ("DANG NING SHENG",font));

//添加第二行
table.addCell (new Paragraph ("Sex(CN)",font));
table.addCell (new Paragraph ("男",font));
table.addCell (new Paragraph ("Sex(EN)",font));
table.addCell (new Paragraph ("MALE",font));
//添加第8行
table.addCell (new Paragraph ("Note",font));
cell = new PdfPCell (new Paragraph ("儿童资料",font));
cell.setColspan (3);
table.addCell (cell);

//添加第9行
table.addCell (new Paragraph ("Pictures",font));
Image photo=Image.getInstance("c:/test/pdf/1246588678828.jpg");
cell = new PdfPCell (photo);
cell.setColspan (3);
table.addCell (cell);

for(PdfPRow row:(ArrayList<PdfPRow>)table.getRows()){
for(PdfPCell cells:row.getCells()){
if(cells!=null){
cells.setPadding(10.0f);
}
}
}

doc.add (table);
doc.newPage();

//插入图片
doc.newPage();
Image image1 = Image.getInstance ("c:/test/pdf/1246588315281.jpg");
image1.setAlignment(image1.ALIGN_CENTER);
image1.scaleToFit( PageSize.A4.getHeight(),PageSize.A4.getWidth());
doc.add (image1);

doc.close ();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值