整理了一下前几天做的一个生成word文档,里面加入了标题图片,仅供参考,一切按项目需求进行改善
import java.awt.Color;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
public class ItextDao {
public JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource){
this.jdbcTemplate=new JdbcTemplate(dataSource);
}
public List<Map<String,Object>> getWord(List<Map<String,object>> list){
Document document=new Document(PageSize.A4);
try{
String timeV=list.get(0).get("bgsj").toString();
//将文件输出流指向一个文件
RtfWriter2.getInstance(document, new FileOutputStream("生成的路径"+timeV+"报告单.doc"));
//打开文档doc
document.open();
//设置标题的格式
Font fontTitle=new Font(Font.NORMAL,40,Font.BOLD,new Color(255,0,0));
Paragraph title=new Paragraph(list.get(0).get("name")+"报告单",fontTitle);
String path="..\\webapps\\AJ\\baogao\\tufashijianbaogaodan\\state.png";
Image dlpic=Image.getInstance("图片路径\state.png");
Image redpic=Image.getInstance("图片路径\red.png");
title.setAlignment(Element.ALIGN_CENTER);//设置样式
dlpic.setAlignment(Image.ALIGN_RIGHT);
redpic.setAlignment(Image.ALIGN_CENTER);
document.add(dlpic);
document.add(title);
document.add(redpic);
//表格添加
document.add(getTable(list));
document.close();
}catch(Exception e){
e.printStackTrace();
}
return list;
}
public Table getTable(List<Map<String,object>> list){
Table table=null;
String bgfs="";
try{
if(list.get(0).get("dh").toString().equals("1")){bgfs="电话";}
if(list.get(0).get("qt").toString().equals("1")){bgfs=bgfs+"/其他";}
table=new Table(4,4);
Cell cell;
table.setPadding(20);
cell=new Cell("时间:");
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell=new Cell(""+list.get(0).get("bgsj"));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(3);
table.addCell(cell);
cell=new Cell("报告类型:");
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell=new Cell(""+list.get(0).get("reportstyle"));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(3);
table.addCell(cell);
cell=new Cell("报告方式:");
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell=new Cell(""+bgfs);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(3);
table.addCell(cell);
cell=new Cell("姓名");
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
cell=new Cell(""+list.get(0).get("tbr"));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);
}catch(Exception e){
e.printStackTrace();
}
return table;
}