文章简介
- 创建pdf并写入内容以及加文本水印
这里采用apache.pdfbox技术实现
创建pdf并写入内容以及加文本水印
/**
* 创建pdf,并写入内容以及水印
*@param dataMap 数据
* @param templateFileName pdf模板
* @param outPutPath 创建pdf位置(包括pdf名字)
* @param templateFile pdf模板路径
* @param text 水印
* @return
*/
public static void exiportPdf(Map<String,Object> dataMap, String templateFileName, String outPutPath, File templateFile,String text ){
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(outPutPath);// 输出流
reader = new PdfReader(templateFile.getAbsolutePath()+"/"+templateFileName);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//设置值
form.setField("title",dataMap.get(SqlStrUtil.SUBBRANCH_URGE_TITLE).toString());
System.out.println(dataMap.get(SqlStrUtil.ACCOMMODATOR).toString());
boolean isSuccesss = form.setField("fiel1",dataMap.get(SqlStrUtil.ACCOMMODATOR).toString());
form.setField("fiel2",dataMap.get(SqlStrUtil.VCARD_NUMBER).toString());
List<Map<String, Object>> recordList = (List<Map<String, Object>>)dataMap.get(SqlStrUtil.RECORDS_LIST);
for(int i = 0;i<recordList.size();i++){
Map<String, Object> objectMap = recordList.get(i);
form.setField("TextArea.0."+i,objectMap.get("Urge_Record").toString());
}
/**********start----设置水印*******************/
// 设置透明度
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.3f);
// 设置字体
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
// 水印的起始
PdfContentByte content = stamper.getOverContent(1);
content.setGState(gs);
content.setFontAndSize(base, 32);
// 开始
content.beginText();
// 设置颜色 默认为黑色
content.setColorFill(BaseColor.BLACK);
// 开始写入水印
content.showTextAligned(Element.ALIGN_MIDDLE, text, 180,
340, 45);
/*content.showTextAligned(Element.ALIGN_MIDDLE, UUID.randomUUID().toString(), 140,
240, 45);*/
content.endText();
/**********end----设置水印*******************/
stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
这里是在某一个方法里面,去掉上面方法的一部分代码:
/*********START************/
String text =recordsDataMap.get(SqlStrUtil.ACCOMMODATOR).toString()+nowdate("yyyyMMdd");
String fullOutputPath = outPutPath + records.vcardNum.replaceAll("\\*","x") + "催收台账.pdf";
File templateFile = new ClassPathResource("file_template").getFile();
PDFUtil.exiportPdf(recordsDataMap, "催收记录模板.pdf", fullOutputPath, templateFile,text);
docFileName.add(fullOutputPath);
/*********END************/
我们用wsp创建了一个pdf模板后,还需要用Adobe Acrobat DC把pdf弄成一个动态的表单,并且为我们要填充的地方设置一个属性名。
wsp创建pdf模板,如下:
Adobe Acrobat DC把pdf弄成一个动态的表单,如下:
保存后,如下:
执行完程序,效果如下: