java 模板生成pdf文件
1.准备工作
1.1 安装Adobe Acrobat pro软件:用来制作导出模板
1.2 用word 制作自己需要的模板,转成pdf格式
1.3 使用Adobe Acrobat pro打开PDF
1.4 复选框勾选
链接: 复选框勾选.
2.java代码
2.1 pom文件
<!-- pdf样式 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!--pdf相关操作-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
2.2生成代码
/** * 生成pdf文件 * * @param map 模板中数据的键值对 map 中存入两个键值对 文字填充("data",Map)图片填充("image",Map) * @param templatePath 模板路径 * @return */
public static ByteArrayOutputStream generatePdf(Map<String, Map> map, String templatePath) {
//生产pdfreader
PdfReader reader = null;
try {
reader = new PdfReader(templatePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* 读取*/
PdfStamper pdfStamper = new PdfStamper(reader, bos);
/*设置字体格式*/
BaseFont baseFont = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<>();
fontList.add(baseFont);
AcroFields s = pdfStamper.getAcroFields();
s.setSubstitutionFonts(fontList);
/*Field , 这个是自己在pdf上定义的变量名称*/
// 处理数据
Map data = map.get("data");
for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {
if (!CollectionUtils.isEmpty(data) && data.get(entry.getKey()) != null) {
s.setField(entry.getKey(), data.get(entry.getKey()).toString(), true);
}
}
// 处理图片
Map imageMap = map.get("image");
for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {
if (!CollectionUtils.isEmpty(imageMap) && imageMap.get(entry.getKey()) != null) {
String key = entry.getKey();
String value = imageMap.get(entry.getKey()).toString();
int pageNo = s.getFieldPositions(key).get(0).page;
Rectangle signRect = s.getFieldPositions(key).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
//根据路径读取图片
Image image = Image.getInstance(value);
//获取图片页面
PdfContentByte under = pdfStamper.getOverContent(pageNo);
//图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
}
pdfStamper.setFormFlattening(true);
pdfStamper.close();
return bos;
} catch (Exception e) {
log.info("pdf文件生成失败");
e.printStackTrace();
}
return null;
}
2.3 输出到本地
/** * 输出本地 * * @param bos pdf字节流 * @throws DocumentException * @throws IOException */
private void extracted(ByteArrayOutputStream bos) {
Document doc = new Document();
// 输出流
FileOutputStream out = null;
try {
// 本地输出路径(可根据自己需要自定义)
out = new FileOutputStream("F:\\" + System.currentTimeMillis() + ".pdf");
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
2.4 浏览器下载 (ajax请求无法下载)
/** * 浏览器下载 * * @param response * @param request * @param fileName 下载的文件名 * @param bos paf字节流 * @return */
public static void getResponse(HttpServletResponse response, HttpServletRequest request, String fileName, ByteArrayOutputStream bos) {
try {
//将文件读入文件流
InputStream inStream = new ByteArrayInputStream(bos.toByteArray());
//获得浏览器代理信息
final String userAgent = request.getHeader("USER-AGENT");
//判断浏览器代理并分别设置响应给浏览器的编码格式
String finalFileName = null;
if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
//IE浏览器
finalFileName = URLEncoder.encode(fileName, "UTF8");
} else if (StringUtils.contains(userAgent, "Mozilla")) {
//google,火狐浏览器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
//其他浏览器
finalFileName = URLEncoder.encode(fileName, "UTF8");
}
//设置HTTP响应头
//告知浏览器下载文件,而不是直接打开,浏览器默认为打开
response.setContentType("application/x-download");
//下载文件的名称
response.addHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");
// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
while ((len = inStream.read(b)) > 0) {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(b, 0, len);
outputStream.flush();
}
inStream.close();
response.getOutputStream().close();
} catch (Exception e) {
throw new CustomException("浏览器下载失败");
}
}