您的位置:首页 > 其它

[转]IText导出word之页眉页脚页码

2013-04-26 08:54 531 查看
本文主要通过Itext jar包对已有数据进行封装并导出rtf文档。rtf也可以用office打开。

代码中包含了设置页眉页脚、添加table等

详细见源码:内含注释说明

/**
* WordServer.java
* 版权所有(C) 2012
* 创建:cuiran 2012-11-07 13:20:40
*/  www.2cto.com
package com.cayden.web.base;

import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cayden.web.action.qybj.QueryProducesAction;
import com.cayden.web.domain.qybj.QybjCompany;
import com.cayden.web.domain.qybj.QybjProduce;
import com.cayden.web.domain.qybj.QybjProduceDevice;
import com.cayden.web.domain.qybj.QybjProduceParam;
import com.cayden.web.dto.qybj.QybjProduceDto;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.field.RtfPageNumber;
import com.lowagie.text.rtf.field.RtfTotalPageNumber;
import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter;

/**
* IText
* 数据导出word类
* @author cuiran
* @version TODO
*/
public class WordServer {
private static Log log = LogFactory.getLog(WordServer.class.getName());
/**
*
* 创建word文档
* @param filename 文件名称
* @param dto 数据封装对象
* @throws DocumentException
* @throws IOException
*/
public String createRTFContext(String filename,QybjProduceDto dto) throws DocumentException,IOException {
String path="";
String imagepath="";
try{
/**
* 先获取对象
*/
QybjProduce qybjProduce=dto.getQybjProduce();
List<QybjProduceDevice> devices=dto.getPdevices();
List<QybjProduceParam>   params=dto.getPparams();
QybjCompany qybjCompany=dto.getQybjCompany();

/**
* 获取导出文件路径
*/
URL url=WordServer.class.getClassLoader().getResource("") ;
path=url.getPath().replace("WEB-INF/classes/", "file/"+filename + ".rtf");
imagepath=url.getPath().replace("WEB-INF/classes/", qybjCompany.getImagepath());
Document document = new Document(PageSize.A4);

RtfWriter2 rtfWriter2=RtfWriter2.getInstance(document, new FileOutputStream(path));

document.open();

// 设置中文字体

BaseFont bfChinese = BaseFont.createFont("STSongStd-Light",

"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

// 标题字体风格

Font titleFont = new Font(bfChinese, 12, Font.BOLD);

Font titleBaoFont = new Font(bfChinese, 20, Font.BOLD);

Font underLineFont = new Font(bfChinese, 12, Font.UNDERLINE);

// 正文字体风格

Font contextFont = new Font(bfChinese, 10, Font.NORMAL);

// 正文标题1 风格

Font contextTitle1Font = new Font(bfChinese, 12, Font.NORMAL);

//设置加粗字体
Font boldFont = new Font(bfChinese, 10, Font.BOLD);

/**
* 测试部分
*/
//          Paragraph title = new Paragraph("标题");
//          // 设置标题格式对齐方式
//          title.setAlignment(Element.ALIGN_CENTER);
//          title.setFont(titleFont);
////            document.add(title);
//          String contextString = "iText是一个能够快速产生PDF文件的java类库。iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的。它的类库尤其与java Servlet有很好的给合。使用iText与PDF能够使你正确的控制Servlet的输出。";
//          Paragraph context = new Paragraph(contextString);
//          // 正文格式左对齐
//          context.setAlignment(Element.ALIGN_LEFT);
//          context.setFont(contextFont);
//          // 离上一段落(标题)空的行数
//          context.setSpacingBefore(20);
//          // 设置第一行空的列数
//          context.setFirstLineIndent(20);
////            document.add(context);

/**
* 设置正文
*/
Paragraph producename = new Paragraph(qybjProduce.getProducename(), titleFont);
document.add(producename);
Paragraph  bjpriceText =  new Paragraph("    报     价:", titleFont);
Paragraph  bjprice = new Paragraph(qybjProduce.getPrice(), underLineFont);
Paragraph  bjdateText =   new Paragraph("     报价日期:", titleFont);
Paragraph  bjdate = new Paragraph(qybjProduce.getBjdate(), underLineFont);
Paragraph customerText = new Paragraph("    客户单位:", titleFont);
Paragraph customer = new Paragraph(qybjProduce.getCompany(), underLineFont);
Paragraph linkManText = new Paragraph("     联 系 人:", titleFont);
Paragraph linkMan = new Paragraph(qybjProduce.getLinkman(), underLineFont);

Paragraph faxText = new Paragraph("    传    真:", titleFont);
Paragraph fax = new Paragraph(qybjProduce.getLinkfax(), underLineFont);
Paragraph linkPhoneText = new Paragraph("     联系电话:", titleFont);
Paragraph linkPhone = new Paragraph(qybjProduce.getLinkphone(), underLineFont);

Paragraph bjCol=new Paragraph();
bjCol.add(bjpriceText);
bjCol.add(customerText);
bjCol.add(faxText);

/**
* 用table
*/
Table tableProduce = new Table(4,3);
float[] widths = { 0.2f, 0.4f, 0.2f, 0.2f };
tableProduce.setWidths(widths);
tableProduce.setBorderWidth(1);
tableProduce.setBorder(0);
tableProduce.setBorderColor(Color.BLACK);
tableProduce.setPadding(0);
tableProduce.setSpacing(0);
tableProduce.setWidth(100f);

Cell cell0 = new Cell();//报价标签单元格
cell0.add(bjpriceText);
//            cell0.setBorderWidth(0f);
tableProduce.addCell(cell0);

cell0 = new Cell();//报价价格单元格
cell0.add(bjprice);
//            cell0.setBorderWidth(0f);
tableProduce.addCell(cell0);

cell0 = new Cell();//报价日期标签单元格
cell0.add(bjdateText);
tableProduce.addCell(cell0);

cell0 = new Cell();//报价日期单元格
cell0.add(bjdate);
tableProduce.addCell(cell0);

cell0 = new Cell();//客户单位标签 单元格
cell0.add(customerText);
tableProduce.addCell(cell0);

cell0 = new Cell();//客户单位单元格
cell0.add(customer);
tableProduce.addCell(cell0);

cell0 = new Cell();//联系人标签 单元格
cell0.add(linkManText);
tableProduce.addCell(cell0);

cell0 = new Cell();//联系人单元格
cell0.add(linkMan);
tableProduce.addCell(cell0);

cell0 = new Cell();//传真标签 单元格
cell0.add(faxText);
tableProduce.addCell(cell0);

cell0 = new Cell();//传真单元格
cell0.add(fax);
tableProduce.addCell(cell0);

cell0 = new Cell();//联系电话标签 单元格
cell0.add(linkPhoneText);
tableProduce.addCell(cell0);

cell0 = new Cell();//联系电话单元格
cell0.add(linkPhone);
tableProduce.addCell(cell0);

document.add(tableProduce);

/**
* 添加生产线备注
*/
Paragraph   remarkText =    new Paragraph(qybjProduce.getRemark(), contextFont);

remarkText.setAlignment(Paragraph.ALIGN_CENTER);
document.add(remarkText);

Paragraph   paramTitleText =    new Paragraph("一.   主要技术参数:", contextTitle1Font);

document.add(paramTitleText);

/**
* 添加技术参数table
*/
Table tableMainParam = new Table(3,params.size());
float[] widthMainParams = { 0.08f, 0.3f, 0.62f};
tableMainParam.setWidths(widthMainParams);
tableMainParam.setBorderWidth(1);
tableMainParam.setBorder(0);
tableMainParam.setBorderColor(Color.BLACK);
tableMainParam.setPadding(0);
tableMainParam.setSpacing(0);
tableMainParam.setWidth(100f);

for(int i=0;i<params.size();i++){
Cell cellParam = new Cell();//单元格

QybjProduceParam param=params.get(i);
Paragraph xuhaoText = new Paragraph((i+1)+".", contextFont);
cellParam.add(xuhaoText);
tableMainParam.addCell(cellParam);

cellParam = new Cell();//参数名字
Paragraph paramNameText = new Paragraph(param.getParamename(), contextFont);
cellParam.add(paramNameText);
tableMainParam.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph paramValueText = new Paragraph(param.getParamevalue(), contextFont);
cellParam.add(paramValueText);
tableMainParam.addCell(cellParam);

}
document.add(tableMainParam);

/**
* 添加设备配置 1、
*/
Paragraph  deviceTitleText =    new Paragraph("二.   设备配置: ", contextTitle1Font);
document.add(deviceTitleText);
/**
* 添加设备配置 2、
*/
Table tableDevice = new Table(7,devices.size());
float[] widthDevices = { 0.04f, 0.2f,0.2f,0.08f,0.08f, 0.2f,0.2f};
tableDevice.setWidths(widthDevices);
tableDevice.setBorderWidth(1);
tableDevice.setBorder(0);
tableDevice.setBorderColor(Color.BLACK);
tableDevice.setPadding(0);
tableDevice.setSpacing(0);
tableDevice.setWidth(100f);

/**
* 设置table header
*/
Cell  cellDevice0 = new Cell();
Paragraph xuhao = new Paragraph("序号", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("设备名称", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("规格", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("数量", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("厂牌", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("功能", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

cellDevice0 = new Cell();
xuhao = new Paragraph("备注", contextFont);
xuhao.setAlignment(Paragraph.ALIGN_CENTER);
cellDevice0.add(xuhao);
tableDevice.addCell(cellDevice0);

for(int i=0;i<devices.size();i++){
Cell cellParam = new Cell();//单元格

QybjProduceDevice device=devices.get(i);
Paragraph xuhaoText = new Paragraph((i+1)+".", contextFont);
cellParam.add(xuhaoText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数名字
Paragraph deviceNameText = new Paragraph(device.getDevicename(), contextFont);
cellParam.add(deviceNameText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph sizeText = new Paragraph(device.getSize(), contextFont);
cellParam.add(sizeText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph amountText = new Paragraph(device.getAmount(), contextFont);
cellParam.add(amountText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph factoryText = new Paragraph(device.getFactory(), contextFont);
cellParam.add(factoryText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph funcText = new Paragraph(device.getFunc(), contextFont);
cellParam.add(funcText);
tableDevice.addCell(cellParam);

cellParam = new Cell();//参数值
Paragraph remark1Text = new Paragraph(device.getRemark(), contextFont);
cellParam.add(remark1Text);
tableDevice.addCell(cellParam);

}

document.add(tableDevice);

Paragraph  specsTitleText =    new Paragraph("三.    设备构成规范: ", contextTitle1Font);

document.add(specsTitleText);

Table tableSpecs = new Table(2,devices.size());
float[] widthSpecss = { 0.04f, 0.96f};
tableSpecs.setWidths(widthSpecss);
tableSpecs.setBorderWidth(1);
tableSpecs.setBorder(0);
tableSpecs.setBorderColor(Color.BLACK);
tableSpecs.setPadding(0);
tableSpecs.setSpacing(0);
tableSpecs.setWidth(100f);

for(int i=0;i<devices.size();i++){
Cell cellSpec = new Cell();//单元格
QybjProduceDevice device=devices.get(i);

Paragraph xuhaoText = new Paragraph((i+1)+".", contextFont);
cellSpec.add(xuhaoText);
cellSpec.setRowspan(2);//设置表格为2行
tableSpecs.addCell(cellSpec);

cellSpec = new Cell();//规范名字
Paragraph specNameText = new Paragraph(device.getSpecname(), contextFont);
cellSpec.add(specNameText);
tableSpecs.addCell(cellSpec);

cellSpec = new Cell();//规范内容
Paragraph specsText = new Paragraph(device.getSpecs(), contextFont);
cellSpec.add(specsText);
tableSpecs.addCell(cellSpec);
}

document.add(tableSpecs);
/**
* 设置页眉
*/

Image headerImage = Image.getInstance(imagepath);

Paragraph headerPara2 = new Paragraph(qybjCompany.getCompanyname(), titleFont);
headerPara2.setAlignment(HeaderFooter.ALIGN_CENTER);

RtfHeaderFooter header1 = new RtfHeaderFooter(headerImage);

Paragraph headerPara1 = new Paragraph();
headerPara1.add(headerPara2);
headerPara1.add(header1);
headerPara1.setAlignment(HeaderFooter.ALIGN_CENTER);

Phrase headerPara = new Phrase();

/**
* 插入表格
* 三列二行
*/
Table table = new Table(3,2);

table.setBorderWidth(1);
table.setBorder(0);
table.setBorderColor(Color.BLACK);
table.setPadding(0);
table.setSpacing(0);
//                 table.setAlignment(Table.ALIGN_MIDDLE);

table.setWidth(100f);
Cell cell = new Cell(headerPara1);//单元格
//                 cell.setBorderWidth(0f);  //设置表格没有边框

cell.setHeader(true);
cell.setRowspan(2);//当前单元格占两行,纵向跨度
table.addCell(cell);
table.endHeaders();// 表头结束

Cell cellHeader = new Cell();
Paragraph produceTitle=  new Paragraph(qybjProduce.getProducename(),titleFont);
produceTitle.setAlignment(HeaderFooter.ALIGN_CENTER);
cellHeader.add(produceTitle);
table.addCell(cellHeader);

cellHeader = new Cell();
Paragraph parafooter = new Paragraph();
parafooter.add(new Phrase("共"));
parafooter.add(new RtfTotalPageNumber());//共几页
parafooter.add(new Phrase("页"));
parafooter.setAlignment(1);
cellHeader.add(parafooter);
table.addCell(cellHeader);

cellHeader = new Cell();
Paragraph pTitle=  new Paragraph("报价单",titleBaoFont);
pTitle.setAlignment(1);
cellHeader.add(pTitle);
cellHeader.setUseAscender(true);
cellHeader.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cellHeader.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cellHeader);

cellHeader = new Cell();
Paragraph para1footer = new Paragraph();
para1footer.add(new Phrase("第"));
para1footer.add(new RtfPageNumber());//第几页
para1footer.add(new Phrase("页"));
para1footer.setAlignment(1);
cellHeader.add(para1footer);
cellHeader.setUseAscender(true);
cellHeader.setHorizontalAlignment(Element.ALIGN_CENTER); //水平居中
cellHeader.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中

table.addCell(cellHeader);

headerPara.add(table);
HeaderFooter header = new HeaderFooter(headerPara,false);

header.setAlignment(HeaderFooter.ALIGN_CENTER);

document.setHeader(header);

/**
* 设置页脚
*/
Paragraph footerPara1 = new Paragraph("公司地址: "+qybjCompany.getCompanyaddr(), contextFont);
Paragraph footerPara2 = new Paragraph("销售热线: "+qybjCompany.getMoblephone()+"    "+qybjCompany.getLegalperson(), contextFont);
Paragraph footerPara3 = new Paragraph("此报价自报价之日起一个月内有效", titleFont);
Paragraph footerPara = new Paragraph();
footerPara.add(footerPara1);
footerPara.add(footerPara2);
footerPara.add(footerPara3);

HeaderFooter footer = new HeaderFooter(footerPara,false);

footer.setAlignment(HeaderFooter.ALIGN_LEFT);
document.setFooter(footer);

// //在表格末尾添加图片

//          Image png = Image.getInstance("c:/1.png");
//
//          document.add(png);

document.close();

}catch (Exception e) {
// TODO: handle exception
log.error("导出word出现异常:", e);
}

return path;
}

/**
* TODO
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

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