最近在做基于三方存证机构的pdf电子合同签署,遇到需要在指定位置动态添加文本的需求,废话不多说,上代码
/**
* 指定位置插入文本
*
* @param text
* 添加文本
* @param page
* 页码
* @param llx
* 文本矩形坐标
* @param lly
* 文本矩形坐标
* @param urx
* 文本矩形坐标
* @param ury
* 文本矩形坐标
* @param pdfFile
* 文件
*
* @return
*/
public static byte[] addContent(String text, int page, float llx, float lly, float urx, float ury, byte[] pdfFile) {
PdfReader reader = null;
PdfStamper stamper = null;
PdfContentByte over = null;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
reader = new PdfReader(pdfFile);
stamper = new PdfStamper(reader, bos);
over = stamper.getOverContent(page);
ColumnText columnText = new ColumnText(over);
// llx 左侧边框距离 lly下侧边框距离 urx 右侧边框距离 ury 上测边框距离
// columnText.setSimpleColumn(115, 120, 300, 185);
columnText.setSimpleColumn(llx, lly, urx, ury);
Paragraph elements = new Paragraph(text);
Font font = new Font(getPdfChineseFont(), 10f, Font.NORMAL, BaseColor.BLACK);
elements.setFont(font);
columnText.addElement(elements);
columnText.go();
stamper.close();
return bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
log.error("指定位置插入文本异常 :" + e);
} finally {
if (reader != null) {
reader.close();
}
}
return pdfFile;
}
public static BaseFont getPdfChineseFont() {
BaseFont baseFont = null;
try {
baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return baseFont;
}