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: 效果

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/355299.html
標籤:其他
上一篇:MySQL筆記 —— jdbc工具類(網站的修改密碼,注冊賬號,注銷賬號功能)
下一篇:day01(Java基礎)
