//横版pdf模板地址
private static String horiPdfTemp = PropertiesLoader.getString("hori.pdf.temp");
//下方图片
private static String downImg = PropertiesLoader.getString("hori.down.img");
public static InputStream templetreq(HoriPdfModel horiPdfModel) throws Exception {
Map<String, Object> map = new HashMap<>();
map = beanToMap(horiPdfModel);
PdfReader reader = new PdfReader(horiPdfTemp);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
AcroFields s = ps.getAcroFields();
s = setFieldHori(s, map, ps);
ps.setFormFlattening(true);
ps.close();
InputStream inputStream = new ByteArrayInputStream(bos.toByteArray());
return inputStream;
}
/**
* 对模板中字段设置对应的value
*
* @param form
* @param hashMap
* @return
* @Description (详细说明)
* @Date 2017年3月29日 下午1:48:25
*/
@SuppressWarnings("unchecked")
public static AcroFields setFieldHori(AcroFields form, Map<String, Object> hashMap, PdfStamper pdfStamper) {
Set<String> it = hashMap.keySet();
Iterator<String> itr = it.iterator();
while (itr.hasNext()) {
try {
Object temp = itr.next();
Object tempValue = hashMap.get(temp);
if (hashMap.get(temp.toString()) != null && !hashMap.get(temp.toString()).equals("null")) {
if (tempValue instanceof ProjectListModel) {
insertTable(form, tempValue, pdfStamper);
} else {
setPdfFont(form, temp.toString(), (String) hashMap.get(temp.toString()), 8, 0);
String sj = hashMap.get("billDate").toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(sj));
setPdfFont(form, "n", String.valueOf(cal.get(Calendar.YEAR)), 8, 0);
setPdfFont(form, "y", String.valueOf(cal.get(Calendar.MONTH) + 1), 8, 0);
setPdfFont(form, "r", String.valueOf(cal.get(Calendar.DATE)), 8, 0);
}
}
} catch (Exception e) {
logger.error("设置模板字段失败", e);
throw new ServiceException("设置模板字段失败");
}
}
return form;
}
public static void insertTable(AcroFields form, Object tempValue, PdfStamper pdfStamper) throws IOException, DocumentException {
/**
* 添加表格
*/
String fonts = getChineseFont(0);//获取字体
BaseFont bf = BaseFont.createFont(fonts, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//创建字体
AcroFields.FieldPosition fieldPosition = form.getFieldPositions("projects").get(0);
Font keyfont = new Font(bf, 8, Font.NORMAL);
float width = fieldPosition.position.getRight() - fieldPosition.position.getLeft();
List dateList = ((ProjectListModel) tempValue).getProjectName();
PdfPTable table = new PdfPTable(dateList.size());
table.setTotalWidth(width);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
if (dateList != null && dateList.size() > 0) {//循环第一行
for (int i = 0; i < dateList.size(); i++) {
String date = dateList.get(i).toString();
PdfPCell cell = createCell(date, keyfont);
table.addCell(cell);
}
List<ProjectValListModel> valListModels = ((ProjectListModel) tempValue).getProjectVal();
for (int i = 0; i < valListModels.size(); i++) {//循环除第一行外的值
List list = (List) valListModels.get(i);
for (int j = 0; j < list.size(); j++) {
table.addCell(createCell(list.get(j), keyfont));
}
}
}
//插入文档
PdfContentByte cb = pdfStamper.getOverContent(1);
table.writeSelectedRows(0, -1, 0, -1, fieldPosition.position.getLeft(), fieldPosition.position.getTop(), cb);
}
/**
* 创建单元格
*
* @param value 显示内容
* @return
*/
private static PdfPCell createCell(Object value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setUseAscender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBorderWidth(0);
cell.setPhrase(new Phrase(getBlank(value), font));
cell.setFixedHeight(15f);// 单元格高度
return cell;
}
/**
* 非空处理
*
* @param value
* @return
*/
private static String getBlank(Object value) {
if (value != null) {
return value.toString();
}
return "";
}
/**
* @param form
* @param dataName 参数名称
* @param data 参数
* @param font 字体大小
*/
public static void setPdfFont(AcroFields form, String dataName, String data, Integer font, int isOut) {
BaseFont bf = null; // 创建字体
String fonts = getChineseFont(isOut);
try {
bf = BaseFont.createFont(fonts, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
form.setFieldProperty(dataName, "textfont", bf, null); // 设置字体
form.setFieldProperty(dataName, "textsize", (float) font, null); // 设置字体大小
//BaseColor red = BaseColor.RED; // 设置字体颜色
//form.setFieldProperty(temp.toString(),"textcolor", red, null);
form.setField(dataName, data);
} catch (Exception e) {
logger.error("设置字体失败", e);
throw new ServiceException("设置字体失败");
}
}
public static <T> Map beanToMap(T bean) {
Map<String, Object> map = new HashMap<>();
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key + "", beanMap.get(key));
}
return map;
}
/**
* 获取中文字体位置
*
* @return
*/
private static String getChineseFont(int isOut) {
String f = "";
if (isOut == 0) {//黑体
f = "SIMHEI.TTF";
} else {//仿宋
f = "simfang.ttf";
}
//宋体(对应css中的 属性 font-family: SimSun; /*宋体*/)
String font1 = "C:/Windows/Fonts/" + f;
//判断系统类型,加载字体文件
Properties prop = System.getProperties();
String osName = prop.getProperty("os.name").toLowerCase();
if (osName.indexOf("linux") > -1) {
font1 = "/usr/share/fonts/" + f;
}
if (!new File(font1).exists()) {
logger.error("字体文件不存在,影响导出pdf中文显示!" + font1);
throw new ServiceException("字体文件不存在,影响导出pdf中文显示!" + font1);
}
return font1;
}
public void insertImage(AcroFields form,PdfStamper pdfStamper) throws DocumentException, IOException {
/**
* 添加图片
*/
int page = form.getFieldPositions("image").get(0).page;
Rectangle signReact = form.getFieldPositions("image").get(0).position;
float x = signReact.getLeft();
float y = signReact.getBottom();
Image image = Image.getInstance(downImg);
PdfContentByte under = pdfStamper.getOverContent(page);
image.scaleToFit(signReact.getWidth(),signReact.getHeight());
image.setAbsolutePosition(x,y);
under.addImage(image);
}
运行:
public static void main( String[] args ) throws Exception {
InputStream inputStream = PDFTempletTicket.templetreq(参数);
}
加入adobe下载地址及补丁地址:
adobe下载地址:https://pan.baidu.com/s/1-HZzCbmrklwGR-8rHM8xYA
补丁下载地址:https://pan.baidu.com/s/1LOf89DdUqACaIt6asxAz8Q
adobe下载完成后选中试用版,将下载下来的补丁文件替换adobe安装目录下的Acrobat里面相同的文件