产品中要求有将表单内容、流转意见等内容放入PDF的功能。由于表单的内容不固定,所以采用PDF模板填充的方式。
填充PDF模板的主要代码:
/** * 填充PDF模板 * * @throws IOException * @throws DocumentException */ public static void fillTemplatePDF(Session session,lotus.domino.Document doc,java.io.InputStream isData,String gwType) throws IOException, DocumentException, Exception { PdfReader reader = new PdfReader(isData); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(String .format(null, TMP_RESULT_MAIN, null))); fill(session,doc, stamper.getAcroFields(),gwType); stamper.setFormFlattening(true); stamper.close(); }
/** * 将模板中的表单字段赋值 */ public static void fill(Session session,lotus.domino.Document doc, AcroFields form,String gwType) throws IOException, DocumentException, Exception { String strFieldName = ""; //使用中文字体 BaseFont bf = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); // BaseFont bf = BaseFont.createFont( "simsun.ttc,0", BaseFont.IDENTITY_H, // BaseFont.NOT_EMBEDDED); for (Iterator it = form.getFields().keySet().iterator(); it.hasNext();) { strFieldName = it.next().toString(); form.setFieldProperty(strFieldName, "textfont", bf, null); if (doc.hasItem(strFieldName)) { Item item = doc.getFirstItem(strFieldName); Vector allvalues = doc.getItemValue(strFieldName); String result = ""; if (allvalues.size() > 0) { int itemType = item.getType(); if(itemType == Item.AUTHORS || itemType==Item.NAMES || itemType==Item.READERS){ Name tmpName = null; StringBuffer sb = new StringBuffer(); for (int i = 0; i < allvalues.size(); i++) { tmpName = session.createName((String) allvalues .get(i)); sb.append(tmpName.getCommon()).append(","); } result = sb.substring(0, sb.lastIndexOf(",")); } else { StringBuffer sb = new StringBuffer(); for (int i = 0; i < allvalues.size(); i++) { if(((String) allvalues.get(i)).indexOf("<tr><td>") != -1){ }else{ sb.append(allvalues.get(i)).append(","); } } result = sb.substring(0, sb.lastIndexOf(",")); } form.setField(strFieldName, result); } } } form.setField("Title", gwType); //设置PDF文档的Title域 }
但有一个问题是:表单内容中如果有图片,那如何插入到PDF模板中的域中呢?
form.setField(strFieldName, result);
这个方法是只能将字符串放入域中。希望高手能给指点一下。