导出PDF (iText实现) PdfDownloadDS

调用:

导出 export-pdf-20141023135557的压缩包,包含PDF文件

多个服务内容在一个Service specification.pdf中

 

@RequestMapping(value = "esbService/exportPdf.do", method = RequestMethod.GET)
@ResponseBody
public void exportPdf(@RequestParam String srvIds, HttpServletResponse response){
	//logger.debug("exportPdf begin ..");
	
	//logger.debug("srvIds : " + srvIds);
	
	if(StringUtils.isNotBlank(srvIds)){
		List<Long> srvIdList = new ArrayList<Long>();
		String[] srvIdArr = srvIds.split(",");
		
		for(String ids : srvIdArr){
			Long id = null;
			try{
				id = Long.parseLong(ids);
			}catch(Exception e){
				logger.error("parse param error .." + e.getMessage());
				continue;
			}
			srvIdList.add(id);
		}
		//logger.debug("parse param pass ..");
		
		List<EsbServiceV> srvList = esbServiceVDS.getServiceList(srvIdList);
		
		// httpheader设置
		// 导出 export-pdf-20141023135557的压缩包,包含PDF文件
		response.setContentType("application/x-msdownload;");  
		response.setHeader("Content-disposition", "attachment; filename = export-pdf-" + String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timestamp) + ".zip");
    
		/*若导出PDF
		response.setContentType("application/pdf");  
		response.setHeader("Content-disposition", "attachment; filename=export-pdf-" + String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", System.currentTimeMillis()) + ".pdf");*/
		
		Map<String, InputStream> in = new HashMap<String, InputStream>();
		try {
			byte[] out = esbPdfDownload.exportPdf(srvList);
			InputStream datas = new ByteArrayInputStream(out);
			in.put("Service specification.pdf", datas);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
        
		//logger.debug("zip file param : " + in);
		//logger.debug("compress file begin ..");
    
		try {
			CompressionUtil.zip2(in, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();			
		}
		
		//logger.debug("compress file end ..");
	}

	//logger.debug("exportPdf end ..");
}

 

MAVEN POM:

<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.4.3</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>	

 

 

 参考:

Java导出pdf (iText.jar)
http://sishuok.com/forum/blogPost/list/4378.html
http://90songjian.blog.51cto.com/2264714/649602

http://blog.csdn.net/uniorg/article/details/2219137
http://hintcnuie.iteye.com/blog/183690
http://quicker.iteye.com/blog/548805

 

工具类:

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.swing.JTextField;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

@Service("iEsbPdfDownload")
public class EsbPdfDownloadDS implements IEsbPdfDownload {

	private static final Logger logger = LoggerFactory.getLogger(EsbPdfDownloadDS.class);
	
	@Autowired
	private IEsbServiceParaDao esbServiceParaDao;
	
	private Document doc = null;
	private String indentation = "   ";
	private BaseFont bfChinese = null;
	private Font fontChinese = null;
	private Font title = null;
	private Font title1 = null;
	private Font tableTitle = null;
	private Font tableFont = null;
	private Font tableEn = null;
	private float[] relativeWidths = null;
	private float[] relativeOutputWidths = null;
	private float[] baseSrvWidths = null;
	private ByteArrayOutputStream byteArray = null;
	private PdfPTable t1 = null;
	
/*程序入口:*/
	@Override
	public byte[] exportPdf(EsbServiceV srv) throws Exception{
		
		writePdfHeader(srv.getServiceNameEn());
		
		//doc.add(new Paragraph("Hello World, Hello iText"));
		
		writeBaseInfo(srv);// 写入基本信息
		// 写输入信息
		writeInputMes(srv);
		// 写输出信息
		writeOutPut(srv);
		
		doc.close();
			
		//byteArray.writeTo(response.getOutputStream());
		//response.getOutputStream().flush();
		return byteArray.toByteArray();
	}
	
	/**
	 * 写文件头 方法名称:writePdfHeader 功能描述:
	 * 
	 * @throws Exception
	 */
	private void writePdfHeader(String srvName) throws Exception {
		logger.debug("writePdfHeader begin ..");
		
		byteArray = new ByteArrayOutputStream();
		doc = new Document(PageSize.A4, 36, 36, 50, 50);
		relativeWidths = new float[] { 6f, 25f, 25f, 18f, 6f, 20f };// 设置表格宽度
		relativeOutputWidths = new float[] { 6f, 25f, 25f, 18f, 26f };// 设置表格宽度
		baseSrvWidths = new float[]{25f,75f};
		PdfWriter.getInstance(doc, byteArray);// 打开监听
		doc.open();
		doc.addTitle(srvName);
		// 设置中文字体
		bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		fontChinese = new Font(bfChinese, 11, Font.NORMAL, BaseColor.BLACK);
		title = new Font(bfChinese, 15, Font.BOLD, BaseColor.BLACK);
		title1 = new Font(bfChinese, 10, Font.BOLD, BaseColor.BLACK);
		
		tableTitle = new Font(bfChinese, 11, Font.BOLD, BaseColor.BLACK);
		tableFont = new Font(bfChinese, 10, Font.NORMAL, BaseColor.BLACK);
		tableEn = new Font();
		tableEn.setSize(9);
		
		logger.debug("writePdfHeader end ..");
	}
		
	/**
	 * 写输出参数信息 方法名称:writeOutPut 功能描述:
	 * 
	 * @param es
	 * @throws Exception
	 */
	private void writeOutPut(EsbServiceV v) throws Exception {
		doc.add(new Paragraph("2.输出", tableFont));
		// doc.add(new Paragraph(" "));
		t1 = getOutputTableHerder("");
		int i = 1;
		List<EsbServiceParameter> dataObject1 = new ArrayList<EsbServiceParameter>();
		List<EsbServiceParameter> outList = getEsbServiceParameter("PARAMETER_OUTPUT", v.getId(), -1L);
		for (EsbServiceParameter sp : outList) {
			if (sp.getDataType().trim().equals("COLLECTION") || sp.getDataType().trim().equals("ENTITY")) {
				dataObject1.add(sp);
			}
			writeOutputBody(sp, t1, i);
			i++;
		}
		// 如果没有参数,输出“无”
		if (null != outList && outList.size() > 0) {
			doc.add(new Paragraph(" "));
			doc.add(t1);
		} else {
			doc.add(new Paragraph(indentation + indentation + "无", fontChinese));
		}

		while (dataObject1.size() > 0) {
			i = 1;
			List<EsbServiceParameter> temp = new ArrayList<EsbServiceParameter>();
			EsbServiceParameter p = dataObject1.get(0);
			String title = p.getParameterNameCh().equals(p.getParameterNameEn()) ? p.getParameterNameEn() : p.getParameterNameCh() + "(" + p.getParameterNameEn() + ")";
			
			PdfPTable t = getOutputTableHerder(title);
			List<EsbServiceParameter> inListNode1 = getEsbServiceParameter("PARAMETER_OUTPUT", v.getId(), p.getId());
			for (EsbServiceParameter sp : inListNode1) {
				if (sp.getDataType().trim().equals("COLLECTION") || sp.getDataType().trim().equals("ENTITY")) {
					temp.add(sp);
				}
				writeOutputBody(sp, t, i);
				i++;
			}
			doc.add(t);
			dataObject1.remove(0);
			// 调整输出顺序
			for (EsbServiceParameter sp : dataObject1) {
				temp.add(sp);
			}
			dataObject1 = temp;
		}
	}
	
	
	private PdfPTable getOutputTableHerder(String mes) throws DocumentException {
		PdfPTable t1 = new PdfPTable(5);
		t1.setWidthPercentage(95f);
		t1.setWidths(relativeOutputWidths);

		// 设置标题信息
		if (!"".equals(mes)) {
			Font ft = null;
			if(mes.indexOf("(") >= 0){
				ft = tableTitle;
			}else{
				ft = tableEn;
			}
			PdfPCell p = new PdfPCell(new Paragraph(mes, ft));
			p.setColspan(5);
			p.setBorder(0);
			t1.addCell(p);
		}

		// ///////////表头
		PdfPCell p1 = new PdfPCell(new Paragraph("序号", tableTitle));
		p1.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p1);

		PdfPCell p3 = new PdfPCell(new Paragraph("字段名称", tableTitle));
		p3.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p3);

		PdfPCell p4 = new PdfPCell(new Paragraph("字段描述", tableTitle));
		p4.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p4);

		PdfPCell p5 = new PdfPCell(new Paragraph("数据类型", tableTitle));
		p5.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p5);

		PdfPCell p6 = new PdfPCell(new Paragraph("备注", tableTitle));
		p6.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p6);

		return t1;
	}
	
	/**
	 * 写输入参数 方法名称:writeInputMes 功能描述:
	 * 
	 * @param es
	 * @throws Exception
	 */
	private void writeInputMes(EsbServiceV srv) throws Exception {
		doc.add(new Paragraph("2.输入", tableFont));
		// doc.add(new Paragraph(" "));
		t1 = getInputTableHerder("");
		// 获取输入参数,一级参数
		int i = 1;
		List<EsbServiceParameter> dataObject = new ArrayList<EsbServiceParameter>();
		List<EsbServiceParameter> inList = getEsbServiceParameter("PARAMETER_INPUT", srv.getId(), -1L);
		for (EsbServiceParameter sp : inList) {
			if (sp.getDataType().trim().equals("COLLECTION") || sp.getDataType().trim().equals("ENTITY")) {
				dataObject.add(sp);
			}
			writeInputBody(sp, t1, i);
			i++;
		}
		// 如果没有参数,输出“无”
		if (null != inList && inList.size() > 0) {
			doc.add(new Paragraph(" "));
			doc.add(t1);
		} else {
			doc.add(new Paragraph("无", fontChinese));
		}
		while (dataObject.size() > 0) {
			i = 1;
			List<EsbServiceParameter> temp = new ArrayList<EsbServiceParameter>();
			EsbServiceParameter p = dataObject.get(0);
			String title = p.getParameterNameCh().equals(p.getParameterNameEn()) ? p.getParameterNameEn() : p.getParameterNameCh() + "(" + p.getParameterNameEn() + ")";
			
			PdfPTable t = getInputTableHerder(title);
			List<EsbServiceParameter> inListNode = getEsbServiceParameter("PARAMETER_INPUT", srv.getId(), p.getId());
			for (EsbServiceParameter sp : inListNode) {
				if (sp.getDataType().trim().equals("COLLECTION") || sp.getDataType().trim().equals("ENTITY")) {
					temp.add(sp);
				}
				writeInputBody(sp, t, i);
				i++;
			}
			doc.add(t);
			dataObject.remove(0);
			// 调整输出顺序
			for (EsbServiceParameter sp : dataObject) {
				temp.add(sp);
			}
			dataObject = temp;
		}
	}
	
	private List<EsbServiceParameter> getEsbServiceParameter(String parameterType, Long srvId , Long parentParameterId) {
		List<EsbServiceParameter> list = new ArrayList<EsbServiceParameter>();
		String hql = "from EsbServiceParameter o where o.serviceId = "+ srvId +" and o.parameterType = '"+parameterType+"' and o.parameterParentId = "+parentParameterId+" and o.enabledFlag='Y' order by o.id asc";
		list = (List<EsbServiceParameter>) esbServiceParaDao.findByHql(hql);
		return list;
	}
	
	/**
	 * 写表体 方法名称:writeBody 功能描述:
	 * 
	 * @param sp
	 * @param t1
	 * @param i
	 * @throws DocumentException
	 */
	private void writeInputBody(EsbServiceParameter sp, PdfPTable t1, int i) throws DocumentException {
		t1.addCell(new Paragraph(i + ".", tableEn));
		t1.addCell(new Paragraph(sp.getParameterNameEn(),tableEn));
		String cn = sp.getParameterNameCh().trim();
		if(cn.indexOf("_") >= 0 || "MsgHeader".equals(cn)){
			t1.addCell(new Paragraph(cn, tableEn));
		}else{
			t1.addCell(new Paragraph(cn, tableFont));
		}
//		t1.addCell(new Paragraph(sp.getParameterNameCh(), tableFont));
		String cellText = getCellTextForDataType(sp);
		t1.addCell(new Paragraph(cellText, tableEn));
		t1.addCell(new Paragraph(sp.getIsNullFlag(), tableFont));
		t1.addCell(new Paragraph(sp.getConstraints(), tableFont));
		// doc.add(t1);
	}
	
	/**
	 * 写表体 方法名称:writeBody 功能描述:
	 * 
	 * @param sp
	 * @param t1
	 * @param i
	 * @throws DocumentException
	 */
	private void writeOutputBody(EsbServiceParameter sp, PdfPTable t1, int i) throws DocumentException {
		t1.addCell(new Paragraph(i + ".", tableEn));
		t1.addCell(new Paragraph(sp.getParameterNameEn(), tableEn));
		String cn = sp.getParameterNameCh().trim();
		if(cn.indexOf("_") >= 0 || "MsgHeader".equals(cn)){
			t1.addCell(new Paragraph(cn, tableEn));
		}else{
			t1.addCell(new Paragraph(cn, tableFont));
		}
		
		String cellText = getCellTextForDataType(sp);
		t1.addCell(new Paragraph(cellText, tableEn));
		t1.addCell(new Paragraph(sp.getRemark(), tableFont));
		// doc.add(t1);
	}
	
	private String getCellTextForDataType(EsbServiceParameter sp) {
		String cellText = "";
		String dataType = sp.getDataType();
		if (Constants.SRV_PARAM_DATA_TYPE_VARCHAR.equals(dataType) || Constants.SRV_PARAM_DATA_TYPE_VARCHAR2.equals(dataType)) {
			Long len = sp.getDataLength();
			if (len != null) {
				cellText = dataType + "(" + len + ")";
			} else {
				cellText = dataType;
			}
			return cellText;
		}
		cellText = dataType;
		return cellText;
	}
	
	private PdfPTable getInputTableHerder(String mes) throws DocumentException {
		PdfPTable t1 = new PdfPTable(6);
		t1.setWidthPercentage(95f);
		t1.setWidths(relativeWidths);

		// 设置标题信息
		if (!"".equals(mes)) {
			Font ft = null;
			if(mes.indexOf("(") >= 0){
				ft = tableTitle;
			}else{
				ft = tableEn;
			}
			PdfPCell p = new PdfPCell(new Paragraph(mes, ft));
			p.setColspan(6);
			p.setBorder(0);
			t1.addCell(p);
		}

		// ///////////表头
		PdfPCell p1 = new PdfPCell(new Paragraph("序号", tableTitle));
		p1.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p1);

		PdfPCell p3 = new PdfPCell(new Paragraph("字段名称", tableTitle));
		p3.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p3);

		PdfPCell p4 = new PdfPCell(new Paragraph("字段描述", tableTitle));
		p4.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p4);

		PdfPCell p5 = new PdfPCell(new Paragraph("数据类型", tableTitle));
		p5.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p5);

		PdfPCell p2 = new PdfPCell(new Paragraph("要求", tableTitle));
		p2.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p2);
		
		PdfPCell p6 = new PdfPCell(new Paragraph("字段约束", tableTitle));
		p6.setBackgroundColor(BaseColor.GRAY);
		t1.addCell(p6);

		return t1;
	}
	
	public String setDefaultValue(String value){
		if(StringUtils.isBlank(value)){
			value = "无";
		}
		return value;
	}
	
	/**
	 * 写服务的基本信息 方法名称:writeBaseInfo 功能描述: 写服务的基本信息
	 * 
	 * @param es
	 * @param i
	 * @throws Exception
	 */
	private void writeBaseInfo(EsbServiceV srv) throws Exception {
		
		PdfPTable t1 = new PdfPTable(2);
		t1.setWidthPercentage(95f);
		t1.setWidths(baseSrvWidths);

		Paragraph pf = new Paragraph();
		pf.setAlignment(Element.ALIGN_CENTER);
		pf.add(new Paragraph(srv.getServiceNameCN(), title));
		PdfPCell name = new PdfPCell(pf);
		name.setColspan(2);
		name.setBorder(0);
		name.setHorizontalAlignment(JTextField.CENTER);
		t1.addCell(name);
		
		PdfPCell p1 = new PdfPCell(new Paragraph("1、服务信息", tableFont));
		p1.setColspan(2);
		p1.setBorder(0);
		t1.addCell(p1);
		
		PdfPCell p11 = new PdfPCell(new Paragraph("服务标识", title1));
		t1.addCell(p11);
		PdfPCell p12 = new PdfPCell(new Paragraph(srv.getServiceNumber(), tableEn));
		t1.addCell(p12);
		
		
		PdfPCell p21 = new PdfPCell(new Paragraph("服务名称", title1));
		t1.addCell(p21);
		PdfPCell p22 = new PdfPCell(new Paragraph(srv.getServiceNameCN() + "(" + srv.getServiceNameEn() + ")", tableFont));
		t1.addCell(p22);
		
		PdfPCell p31 = new PdfPCell(new Paragraph("服务描述", title1));
		t1.addCell(p31);		
		PdfPCell p32 = new PdfPCell(new Paragraph(setDefaultValue(srv.getDescription()), tableFont));
		t1.addCell(p32);
		
		PdfPCell p41 = new PdfPCell(new Paragraph("服务类型", title1));
		t1.addCell(p41);
		PdfPCell p42 = new PdfPCell(new Paragraph(srv.getServiceTypeName(), tableFont));
		t1.addCell(p42);
		
		PdfPCell p51 = new PdfPCell(new Paragraph("同步/异步方式", title1));
		t1.addCell(p51);		
		PdfPCell p52 = new PdfPCell(new Paragraph(setDefaultValue(srv.getSynOrAsyncName()), tableFont));
		t1.addCell(p52);
		
		PdfPCell p61 = new PdfPCell(new Paragraph("实现方式", title1));
		t1.addCell(p61);
		PdfPCell p62 = new PdfPCell(new Paragraph(setDefaultValue(srv.getMethodName()), tableEn));
		t1.addCell(p62);
		
		PdfPCell p71 = new PdfPCell(new Paragraph("业务场景说明", title1));
		t1.addCell(p71);
		PdfPCell p72 = new PdfPCell(new Paragraph(setDefaultValue(srv.getApplicationSence()), tableFont));
		t1.addCell(p72);
		
		PdfPCell p81 = new PdfPCell(new Paragraph("业务规则和逻辑", title1));
		t1.addCell(p81);
		PdfPCell p82 = new PdfPCell(new Paragraph(setDefaultValue(srv.getBussnessLogic()), tableFont));
		t1.addCell(p82);
		
		PdfPCell p91 = new PdfPCell(new Paragraph("出错和异常处理机制", title1));
		t1.addCell(p91);
		PdfPCell p92 = new PdfPCell(new Paragraph(setDefaultValue(srv.getExceptionHandle()), tableFont));
		t1.addCell(p92);
		
		PdfPCell p101 = new PdfPCell(new Paragraph("数据量", title1));
		t1.addCell(p101);
		PdfPCell p102 = new PdfPCell(new Paragraph(setDefaultValue(srv.getDataLength()), tableFont));
		t1.addCell(p102);
		
		PdfPCell p111 = new PdfPCell(new Paragraph("响应时间要求", title1));
		t1.addCell(p111);
		PdfPCell p112 = new PdfPCell(new Paragraph(setDefaultValue(srv.getTimeResponse()), tableFont));
		t1.addCell(p112);
		
		PdfPCell p121 = new PdfPCell(new Paragraph("服务安全和权限要求", title1));
		t1.addCell(p121);
		PdfPCell p122 = new PdfPCell(new Paragraph(setDefaultValue(srv.getSecurityPermission()), tableFont));
		t1.addCell(p122);
		
		PdfPCell p131 = new PdfPCell(new Paragraph("使用建议", title1));
		t1.addCell(p131);
		PdfPCell p132 = new PdfPCell(new Paragraph(setDefaultValue(srv.getSuggestion()), tableFont));
		t1.addCell(p132);
		
		doc.add(t1);

	}
	
	
}

 

 结果样式:


导出PDF (iText实现) PdfDownloadDS
 
导出PDF (iText实现) PdfDownloadDS

 

你可能感兴趣的:(download)