java PDF模板生成并导出(文字表格图片)
Posted や` 紫蕾 'あ
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java PDF模板生成并导出(文字表格图片)相关的知识,希望对你有一定的参考价值。
1:jar包
<!-- itextpdf-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
2:制作一个pdf模板 创建表单–编辑域
3:工具类:
/**
* pdf模板导出
*
* @param map
* @param out
* @throws Exception
*/
public static void creatPdf(Map<String, Object> map, OutputStream out) throws Exception {
try {
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 输出流
// String outPutPath = "/Users/xxx/Desktop/files/pdf模板导出.pdf";
// FileOutputStream out = new FileOutputStream(filePath);
// 读取pdf模板路径
PdfReader reader = new PdfReader(String.valueOf(map.get("tempPath")));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, bos);
stamper.setFormFlattening(true);
AcroFields form = stamper.getAcroFields();
// 文字类的内容处理
Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
}
// 图片类的内容处理
Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
for (String key : imgmap.keySet()) {
String value = imgmap.get(key);
String imgpath = value;
int pageNo = form.getFieldPositions(key).get(0).page;
Rectangle signRect = form.getFieldPositions(key).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 根据路径读取图片
Image image = Image.getInstance(imgpath);
// 获取图片页面
PdfContentByte under = stamper.getOverContent(pageNo);
// 图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
// 表格类
Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) map.get("tableList");
for (String key : listMap.keySet()) {
List<List<String>> lists = listMap.get(key);
int pageNo = form.getFieldPositions(key).get(0).page;
PdfContentByte pcb = stamper.getOverContent(pageNo);
Rectangle signRect = form.getFieldPositions(key).get(0).position;
//表格位置
int column = lists.get(0).size();
int row = lists.size();
PdfPTable table = new PdfPTable(column);
float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
int size = lists.get(0).size();
float width[] = new float[size];
for (int i = 0; i < size; i++) {
if (i == 0) {
width[i] = 60f;
} else {
width[i] = (tatalWidth - 60) / (size - 1);
}
}
table.setTotalWidth(width);
table.setLockedWidth(true);
table.setKeepTogether(true);
table.setSplitLate(false);
table.setSplitRows(true);
Font FontProve = new Font(bf, 10, 0);
//表格数据填写
for (int i = 0; i < row; i++) {
List<String> list = lists.get(i);
for (int j = 0; j < column; j++) {
Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(1);
cell.setVerticalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setLeading(0, (float) 1.4);
table.addCell(cell);
}
}
table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
}
// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.setFormFlattening(true);
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
int pageNum = reader.getNumberOfPages();
for (int i = 1; i <= pageNum; i++) {
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
copy.addPage(importPage);
}
doc.close();
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
4:
/**
* 导出数据 生成pdf
*
* @param response
*/
@ApiOperation(value = "导出数据 生成pdf")
@GetMapping("/exportPdf")
public void exportPdf(HttpServletResponse response) {
// 模板路径
String tempPath = "/Users/xxx/IdeaProjects/test/pdf导出模板.pdf";
//文字类
Map<String, String> dataMap = new HashMap<>();
// dataMap中的key要和模板中的域名对应
dataMap.put("userName", "测试文字内容userName");
// dataMap中的key要和模板中的域名对应
dataMap.put("who", "测试文字内容who");
dataMap.put("demo1", "测试文字内容demo1");
dataMap.put("demo2", "测试文字内容demo2");
dataMap.put("name", "测试文字内容名字");
dataMap.put("address", "测试文字内容地址");
dataMap.put("main", "测试文字内容主要负责人");
dataMap.put("mobile", "测试文字内容电话");
dataMap.put("phone", "测试文字内容手机号");
//图片
String img = "/Users/xxx/Desktop/files/img/123.jpeg";
Map<String, String> imgMap = new HashMap<>();
// imgMap中的key要和模板中的域名对应
imgMap.put("img", img);
//表格 一行数据是一个list
List<String> list = new ArrayList<>();
list.add("标题");
list.add("日期");
list.add("金额");
list.add("备注");
List<String> list2 = new ArrayList<>();
list2.add("标题");
list2.add("2021-08-27");
list2.add("100000");
list2.add("");
List<String> list3 = new ArrayList<>();
list3.add("标题22");
list3.add("2021-08-29");
list3.add("200000");
list3.add("备注");
List<List<String>> List = new ArrayList<>();
List.add(list);
List.add(list2);
List.add(list3);
Map<String, List<List<String>>> listMap = new HashMap<>();
// 这里的listMap中key要和模板中的域名对应
listMap.put("item", List);
Map<String, Object> o = new HashMap<>();
o.put("tempPath", tempPath);
o.put("dataMap", dataMap);
o.put("imgMap", imgMap);
o.put("tableList", listMap);
try {
OutputStream out = response.getOutputStream();
response.setCharacterEncoding("utf-8");
response.setHeader("content-type", "application/octet-stream");
String date = DateUtiles.CurrentDate();
String fileName = URLEncoder.encode("pdf模板导出" + date + ".pdf", "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
try {
PdfUtils.creatPdf(o, out);
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
5: 效果
以上是关于java PDF模板生成并导出(文字表格图片)的主要内容,如果未能解决你的问题,请参考以下文章