Java中使用ItextPdf工具根据PDF合同模板填充pdf

时间:2025-04-09 11:29:03
import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import pojo.user; import java.io.*; import java.util.*; public class PdfUtils { /** * @param map 需要填充的字段 * @param sourceFile 原文件路径 * @param targetFile 目标文件路径 * @param imgURLMap 填充图片路径 * @throws IOException */ public static void genPdf(Map<String, String> map, String sourceFile, String targetFile) throws IOException { File templateFile = new File(sourceFile); fillParam(map, FileUtils.readFileToByteArray(templateFile), targetFile); } /** *使用map中的参数填充pdf,map中的key和pdf表单中的field对应 * @param fieldValueMap * @param file * @param contractFileName * @param imgURLMap //这边暂时吧图片给注释了,如需填充图片直接加参数即可 */ public static void fillParam(Map<String, String> fieldValueMap,byte[] file, String contractFileName) { //输出流 FileOutputStream fos = null; try { fos = new FileOutputStream(contractFileName); //获取PdfReader对象,获取模板位置 PdfReader reader = null; /* 将要生成的目标PDF文件名称 */ PdfStamper stamper = null; BaseFont base = null; //取出模板中的所有字段 AcroFields acroFields = null; // 获取存在resources目录下的pdf模板位置 URL //URL file = ().getResource(""); try { reader = new PdfReader(file); stamper = new PdfStamper(reader, fos); stamper.setFormFlattening(true); //简体中文字体 base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); acroFields = stamper.getAcroFields(); //如果图片放在resources目录下需要这么写 // String imgUrl = new ClassPathResource("static/IMG_5809.JPG").getURL().getPath(); //循环添加公章图片 //for(String key : ()) { // String value = (key).toString(); // //获取图片域名 // position = (key).get(0); // //通过域名获取所在页和坐标,左下角为起点 // int pageNo = ; // Rectangle signRect = ; // float x = (); // float y = (); // //读图片 // Image image = (value); // //获取操作页面 // PdfContentByte under = (pageNo); // //根据域的大小缩放图片 // ((),()); // //添加图片 // (x,y); // (image); // ("--"+key+"---"+value); //} for (String key : acroFields.getFields().keySet()) { acroFields.setFieldProperty(key, "textfont", base, null); //字体大小 acroFields.setFieldProperty(key, "textsize", new Float(12), null); } if (fieldValueMap != null) { for (String fieldName : fieldValueMap.keySet()) { if (StringUtils.isNotBlank(fieldValueMap.get(fieldName))) { //获取map中key对应的Value是否为On,若是则勾选复选框 if (fieldValueMap.get(fieldName).equals("On") || fieldValueMap.get(fieldName) == "On") { acroFields.setField(fieldName, fieldValueMap.get(fieldName),"true"); }else{ acroFields.setField(fieldName, fieldValueMap.get(fieldName)); } } } } } catch (Exception e) { e.printStackTrace(); } finally { if (stamper != null) { try { stamper.close(); } catch (Exception e) { e.printStackTrace(); } } if (reader != null) { reader.close(); } } } catch (Exception e) { System.out.println("填充参数异常"); e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); } } }