pom依赖在这里的第一部分和第二部分
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
/**
* @author aaa
* @create 2018-12-13 18:50
*/
public class PdfHandleUtil {
private static final Logger logger = LoggerFactory.getLogger(PdfHandleUtil.class);
/**
* @param templatePath 文件路径
* @param outputPath 输出路径
* @param fieldsMap 文件填充内容
* @return
* @throws Exception
* pdf文档填充
*/
public static String insertTextFieldsForRealPath(String templatePath, String outputPath, Map<String, String> fieldsMap) throws Exception {
File file = new File(templatePath);
// 1.判断合同模板是否存在
if (!file.isFile()) {
if (logger.isErrorEnabled()) {
logger.error("[{}]合同模版不存在", templatePath);
}
throw new RuntimeException("合同模板文件不存在");
}
// 2.打开pdf读取器
PdfReader reader = new PdfReader(templatePath);
String fileName = file.getName();
// 3.判断文件目录是否存在,否则自动生成
File directory = new File(outputPath);
if (!directory.exists()) {
directory.mkdirs();
}
int floor = (int) Math.floor(Math.random() * 10000);
// 4.加random防文件重名
String[] split = fileName.split("\\.");
fileName = split[0] + floor + "." + split[1];
outputPath = outputPath.concat("_").concat(fileName);
try (FileOutputStream out = new FileOutputStream(outputPath);) {
PdfStamper stamper = new PdfStamper(reader, out);
AcroFields fields = stamper.getAcroFields();
//设置宋体
// BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// fields.setFieldProperty("enterpriseCode", "textfont", bf, null);
// 5.对表单域进行填充
for (String name : fields.getFields().keySet()) {
String value = fieldsMap.get(name);
if (!ObjectUtils.isEmpty(value)) {
fields.setField(name, value, true);
}
}
// 6.如果为false那么生成的PDF文件还能编辑,一定要设为true
stamper.setFormFlattening(true);
stamper.close();
reader.close();
} catch (Exception e) {
logger.error("==>>pdf表单属性填充中发生异常[{}]<<==", e);
throw new RuntimeException("pdf表单属性填充中发生异常", e);
}
return outputPath;
}
}