public ByteArrayOutputStream createPdfStream(String templateFilePath, Map<String, String> resultMap) {
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
String path1 = "D:\\Project\\acpartner\\app\\biz\\shared\\src\\main\\resources\\STFANGSO.ttf";
ByteArrayOutputStream ba = new ByteArrayOutputStream();
PdfReader reader = null;
PdfStamper stamp = null;
try {
reader = new PdfReader(templateFilePath);
stamp = new PdfStamper(reader, ba);
ArrayList<BaseFont> fontList = new ArrayList<>();
BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
BaseFont bf = BaseFont.createFont(path1, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
fontList.add(baseFont);
AcroFields form = stamp.getAcroFields();
if (resultMap != null) {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
if (entry.getKey().equals("partyAName")){
form.setFieldProperty(entry.getKey(),"textsize",32f,null);
form.setFieldProperty(entry.getKey(),"textfont",bf,null);
}
if (entry.getKey().equals("startTime")){
form.setFieldProperty(entry.getKey(),"textfont",bf,null);
form.setFieldProperty(entry.getKey(),"textsize",16f,null);
}
form.setField(entry.getKey(), entry.getValue());
}
}
stamp.setFormFlattening(true);
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (DocumentException documentException) {
documentException.printStackTrace();
}finally {
if (null != stamp) {
try {
stamp.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != reader) {
reader.close();
}
}
return ba;
}
@Test
public void pdfTest() {
Map<String, String> resultMap= new HashMap<>(0);
resultMap.put( "partyAName", "湖人总冠军公司");
resultMap.put( "chainInfo", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
resultMap.put("startTime","2021年1月12日");
resultMap.put("endTime","2022年1月12日");
resultMap.put("chainTime","2022年1月12日");
PDFUtil pdfUtil = new PDFUtil();
try{
String templatePath = "C:\\Users\\wb-pxh\\Downloads\\Distribution_gold.pdf";
ByteArrayOutputStream pdf = pdfUtil.createPdfStream(templatePath, resultMap);
String newPadPath="C:\\Users\\wb-pxh\\Downloads\\pdf2.pdf";
FileOutputStream out = new FileOutputStream(newPadPath);
out.write(pdf.toByteArray());
out.flush();
out.close();
pdf.close();
}catch (Exception e){
e.printStackTrace();
}
}