PDFUtils
public class PDFTempletUtil {
private String templatePdfPath;
private String ttcPath;
private String targetPdfpath;
private static Logger logger=Logger.getLogger(PDFTempletUtil.class);
public PDFTempletUtil() {
super();
}
public PDFTempletUtil(String templatePdfPath, String ttcPath, String targetPdfpath) {
this.templatePdfPath = templatePdfPath;
this.ttcPath = ttcPath;
this.targetPdfpath = targetPdfpath;
}
public void templetTicket(BaseFont bf, File file, String[] picFileds, String signPicPath, String[] fileds,
Map<String, String> mapValues) throws Exception {
PdfReader reader = new PdfReader(templatePdfPath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
FileOutputStream fos = new FileOutputStream(file);
try {
if (bf == null) {
try {
bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
} catch(Exception e) {
bf= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
}
}
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf);
AcroFields s = ps.getAcroFields();
s.setSubstitutionFonts(fontList);
String[] picPaths = signPicPath.split(",");
int len = picPaths.length - 1;
for (int i = 0; i < picFileds.length; i++) {
if (i <= len && !picPaths[i].equals("") && !picFileds[i].equals("")) {
insertImage(ps, s, picPaths[i], picFileds[i]);
}
if (i >= len)
break;
}
for (int i = 0; i < fileds.length; i++) {
if (mapValues.containsKey(fileds[i])) {
s.setField(fileds[i], mapValues.get(fileds[i]));
}
}
ps.setFormFlattening(true);
ps.close();
fos.write(bos.toByteArray());
fos.close();
} catch (Exception e) {
logger.info(e.getMessage());
}finally {
ps.close();
fos.close();
}
}
public static void insertImage(PdfStamper ps, AcroFields s, String picPath, String picField) {
try {
List<AcroFields.FieldPosition> list = s.getFieldPositions(picField);
Rectangle signRect = list.get(0).position;
Image image = Image.getInstance(picPath);
PdfContentByte under = ps.getOverContent(list.get(0).page);
float x = signRect.getLeft();
float y = signRect.getBottom();
image.setAbsolutePosition(x, y);
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
under.addImage(image);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getTemplatePdfPath() {
return templatePdfPath;
}
public void setTemplatePdfPath(String templatePdfPath) {
this.templatePdfPath = templatePdfPath;
}
public String getTtcPath() {
return ttcPath;
}
public void setTtcPath(String ttcPath) {
this.ttcPath = ttcPath;
}
public String getTargetPdfpath() {
return targetPdfpath;
}
public void setTargetPdfpath(String targetPdfpath) {
this.targetPdfpath = targetPdfpath;
}
}