itext操作表单域导出PDF,俗称抠模板

/**
* templateUrl 模板文件路径,包含文件名
* targetUrl 目标路径
* dateMap 填充数据
*/
public class CreatePdfUtil {
public static String createAllPdf(String templateUrl,String targetUrl,HashMap dataMap) throws Exception {
//填充创建pdf
PdfReader reader = null;
PdfStamper stamp = null;
String times = "";
try {
reader = new PdfReader(templateUrl);

SimpleDateFormat simp = new SimpleDateFormat("yyyyMMdd");
times = simp.format(new Date()).trim();
times+=UUIDUtil.getUUID();
times = times;
//创建生成报告名称
String root = targetUrl;
if (!new File(root).exists())
new File(root).mkdirs();
File deskFile = new File(root, times + ".pdf");
stamp = new PdfStamper(reader, new FileOutputStream(deskFile));
PdfWriter writer = stamp.getWriter();
TextField field = new TextField(writer, new Rectangle(200, 200, 400, 300), "field1");
field.setOptions(TextField.MULTILINE);
//取出报表模板中的所有字段
AcroFields form = stamp.getAcroFields();
// 填充数据
transformRegular(form,dataMap);
stamp.setFormFlattening(true);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamp != null) {
stamp.close();
}
if (reader != null) {
reader.close();
}
}
return times;
}

/**
     * 填充规整的表单域
     *
     * @param form
     */
public static void transformRegular(AcroFields form, HashMap dataMap) throws IOException, DocumentException {
if (dataMap == null || dataMap.size() == 0) {
return;
}
// 设置中文显示
BaseFont bfChinese = BaseFont.createFont( "STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
String key = "";
    //注意,设置中文使用下面的方法,form.setFieldProperty(key,"textfont",bfChinese,null)这种方法没作用
        form.addSubstitutionFont(bfChinese);
Iterator ekey = dataMap.keySet().iterator();
Object obj = null ;
while (ekey.hasNext()) {
key = ekey.next().toString();
try {
obj = dataMap.get(key);
//非空放入
if( dataMap.get(key) != null) {
            //form.setFieldProperty(key,"textfont",bfChinese,null);
                    form.setField(key, dataMap.get(key).toString());
}
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
依赖---------
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
注:如果填充时字数太多想要换行,则需在PDF模板里面直接对文本域的样式进行设置,选择允许多行即可。
posted @ 2020-01-13 14:36  三豪  阅读(1202)  评论(0编辑  收藏  举报