import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
public class PdfUtil {
/**
*
* @param o 写入的数据
* @param out 自定义保存pdf的文件流
* @param templatePath pdf模板路径
*/
// 利用模板生成pdf
public void fillTemplate(Map<String,Object> o,ServletOutputStream out,String templatePath) {
PdfReader reader;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
reader = new PdfReader(templatePath);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = ();
<String> it = ().keySet().iterator();
while (()) {
String name = it.next().toString();
(name);
String value = o.get(name)!=null?o.get(name).toString():null;
(name,value);
}
(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
(e);
} catch (DocumentException e) {
(e);
}
}
}