【Java】itext根据模板生成pdf(包括图片和表格)

1、导入需要的jar包:itext-asian-5.2.0.jar itextpdf-5.5.11.jar。

2、新建word文档,创建模板,将文件另存为pdf,并用Adobe Acrobat DC打开编辑,点击右侧【准备表单】后点击【开始】

3、在需要插入数据的空白处,右击,点击【文本域】,将文本域拖放到你想要的位置,更改域名称为你传入的变量名。

4、保存文件,将文件放到项目中。生成pdf代码如下:

 1 public static void creatPdf(Map<String, Object> map,String filePath) {
 2         try {
 3             BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1", BaseFont.IDENTITY_H,
 4                     BaseFont.EMBEDDED);
 5             FileOutputStream out = new FileOutputStream(filePath);// 输出流
 6             PdfReader reader = new PdfReader(TemplateToWord.class.getResource("/com/cn/business/templates/report.pdf"));// 读取pdf模板
 7             ByteArrayOutputStream bos = new ByteArrayOutputStream();
 8             PdfStamper stamper = new PdfStamper(reader, bos);
 9             stamper.setFormFlattening(true);
10             AcroFields form = stamper.getAcroFields();
11             // 文字类的内容处理
12             Map<String, String> datemap = (Map<String, String>) map.get("datemap");
13             form.addSubstitutionFont(bf);
14             for (String key : datemap.keySet()) {
15                 String value = datemap.get(key);
16                 form.setField(key, value);
17             }
18             // 图片类的内容处理
19             Map<String, String> imgmap = (Map<String, String>) map.get("imgmap");
20             for (String key : imgmap.keySet()) {
21                 String value = imgmap.get(key);
22                 String imgpath = value;
23                 int pageNo = form.getFieldPositions(key).get(0).page;
24                 Rectangle signRect = form.getFieldPositions(key).get(0).position;
25                 float x = signRect.getLeft();
26                 float y = signRect.getBottom();
27                 // 根据路径读取图片
28                 Image image = Image.getInstance(imgpath);
29                 // 获取图片页面
30                 PdfContentByte under = stamper.getOverContent(pageNo);
31                 // 图片大小自适应
32                 image.scaleToFit(signRect.getWidth(), signRect.getHeight());
33                 // 添加图片
34                 image.setAbsolutePosition(x, y);
35                 under.addImage(image);
36             }
37             // 表格类
38             Map<String, List<List<String>>> listMap =  (Map<String, List<List<String>>>) map.get("list");
39             for (String key : listMap.keySet()) {
40                 List<List<String>> lists = listMap.get(key);
41                 int pageNo = form.getFieldPositions(key).get(0).page;
42                 PdfContentByte pcb = stamper.getOverContent(pageNo);
43                 Rectangle signRect = form.getFieldPositions(key).get(0).position;
44                 //表格位置
45                 int column = lists.get(0).size();
46                 int row = lists.size();
47                 PdfPTable table =  new PdfPTable(column);
48                 float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
49                 int size = lists.get(0).size();
50                 float width[] = new float[size];
51                 for(int i=0;i<size;i++){
52                     if(i==0){
53                         width[i]=60f;
54                     }else{
55                         width[i]=(tatalWidth-60)/(size-1);
56                     }
57                 }
58                 table.setTotalWidth(width);
59                 table.setLockedWidth(true);
60                 table.setKeepTogether(true);
61                 table.setSplitLate(false);
62                 table.setSplitRows(true);
63                 Font FontProve = new Font(bf, 10, 0);
64                 //表格数据填写
65                 for(int i=0;i<row;i++){
66                     List<String> list = lists.get(i);
67                     for(int j=0;j<column;j++){
68                         Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
69                         PdfPCell cell = new PdfPCell(paragraph);
70                         cell.setBorderWidth(1);
71                         cell.setVerticalAlignment(Element.ALIGN_CENTER);
72                         cell.setHorizontalAlignment(Element.ALIGN_CENTER);
73                         cell.setLeading(0, (float) 1.4);
74                         table.addCell(cell);
75                     }
76                 }
77                 table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
78             }
79             stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
80             stamper.close();
81             Document doc = new Document();
82             PdfCopy copy = new PdfCopy(doc, out);
83             doc.open();
84             int pageNum = reader.getNumberOfPages();
85              for(int i = 1;i <= pageNum;i++){
86                  PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
87                  copy.addPage(importPage);
88              }
89             doc.close();
90         } catch (IOException e) {
91             System.out.println(e);
92         } catch (DocumentException e) {
93             System.out.println(e);
94         }
95 
96     }
View Code

 

参数:

 1 //文字类
 2 Map<String, String> dataMap = new HashMap<String, String>();
 3 dataMap.put("title", title+time);
 4 
 5 //图片
 6 String knowImgPath = "D:\\upload\\report\\knowImg.png";
 7 Map<String, String> imgMap = new HashMap<String, String>();
 8 imgMap.put("knowImg", knowImgPath);
 9 
10 //表格 一行数据是一个list
11 List<String> list = new ArrayList<String>();
12 list.add("日期");
13 list.add("金额");
14 
15 List<String> list2 = new ArrayList<String>();
16 list2.add("2018-01-01");
17 list2.add("100");
18 
19 List<List<String>> List = new ArrayList<List<String>>();
20 List.add(list);
21 List.add(list2);
22 
23 Map<String, List<List<String>>> listMap = new HashMap<String, List<List<String>>>();
24 listMap.put("eventList", List);
25 
26 Map<String, Object> o = new HashMap<String, Object>();
27 o.put("datemap", dataMap);
28 o.put("imgmap", imgMap);
29 o.put("list", listMap);
30 
31 String knowImgPath = "D:\\upload\\report\\report.pdf";
32 creatPdf(o,filePath);
View Code

 

posted @ 2018-07-25 17:21  wkYLduoduo  阅读(10923)  评论(11编辑  收藏  举报