专栏首页故久itext根据模板生成pdf(支持分页)

itext根据模板生成pdf(支持分页)

首先给个效果图吧

第二页

第三页

下面就附上代码把

// 利用模板生成pdf public static void pdfout(Map<String,Object> o,String newPDFPath){ // 模板路径 File file = new File(""); String filePath = null; try { filePath = file.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } System.out.println(filePath); String templatePath = "C:/Users/pc/Desktop/990696 list -1.pdf"; String templatePaths = "C:/Users/pc/Desktop/990696 list -2.pdf"; // 生成的新文件路径 PdfReader reader; PdfReader readers; FileOutputStream out;

ByteArrayOutputStream bos; ByteArrayOutputStream boss; PdfStamper stamper; PdfStamper stamper2; AcroFields form2; int checkSize=0;

List<PdfReader> pdfList = new ArrayList<>(); List<ByteArrayOutputStream> bossList = new ArrayList<>();

try { BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font FontChinese = new Font(bf, 5, Font.NORMAL); out = new FileOutputStream(newPDFPath);// 输出流 reader = new PdfReader(templatePath);// 读取pdf模板

bos = new ByteArrayOutputStream();

stamper = new PdfStamper(reader, bos);

AcroFields form = stamper.getAcroFields();

pdfList.add(reader); bossList.add(bos);

//文字类的内容处理 Map<String,String> datemap = (Map<String,String>)o.get("datemap"); form.addSubstitutionFont(bf); for(String key : datemap.keySet()){ String value = datemap.get(key); form.setField(key,value); }

Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) o.get("list"); for (String key : listMap.keySet()) { System.out.println("key = "+key); // 第一个表单 List<List<String>> lists = listMap.get(key); checkSize = lists.size(); int pageNo1 = form.getFieldPositions(key).get(0).page; PdfContentByte pcb1 = stamper.getOverContent(pageNo1); Rectangle signRect1 = form.getFieldPositions(key).get(0).position; //表格位置 int row1 = 23 ; int column1 = 5; PdfPTable table1 = new PdfPTable(column1); float tatalWidth = signRect1.getRight() - signRect1.getLeft() - 1; int size = 5; float width[] = new float[size]; for (int j = 0; j < size; j++) { if (j == 0) { width[j] = 60f; } else { width[j] = (tatalWidth - 60) / (size - 1); } } table1.setTotalWidth(width); table1.setLockedWidth(true); table1.setKeepTogether(true); table1.setSplitLate(false); table1.setSplitRows(true); Font FontProve = new Font(bf, 10, 0);

// 第二个表单 readers=new PdfReader(templatePaths); boss = new ByteArrayOutputStream(); stamper2 = new PdfStamper(readers, boss);

form2 = stamper2.getAcroFields();

pdfList.add(readers); bossList.add(boss);

int pageNo2 = form2.getFieldPositions(key).get(0).page; PdfContentByte pcb2 = stamper2.getOverContent(pageNo2); Rectangle signRect2 = form2.getFieldPositions(key).get(0).position; System.out.println(pcb2); //表格位置 int column2 = 5;

PdfPTable table2 = new PdfPTable(column2); float tatalWidth2 = signRect2.getRight() - signRect2.getLeft() - 1; int size2 = 5; float width2[] = new float[size2]; for (int j = 0; j < size2; j++) { if (j == 0) { width2[j] = 60f; } else { width2[j] = (tatalWidth2 - 60) / (size2 - 1); } } table2.setTotalWidth(width2); table2.setLockedWidth(true); table2.setKeepTogether(true); table2.setSplitLate(false); table2.setSplitRows(true); Font FontProve2 = new Font(bf, 10,Font.NORMAL, BaseColor.BLACK);

for (int i = 0; i < lists.size(); i++) { // 判断是否大于19行 if (i <= 19) { //每行数据 List<String> listdetail = lists.get(i); for (int j = 0; j <column1; j++) { Paragraph paragraph = new Paragraph(String.valueOf(listdetail.get(j)), FontProve); PdfPCell cell = new PdfPCell(paragraph); if (i == lists.size()-1) { System.out.println("i是:" + lists.size()); cell.setColspan(5); cell.setBorderWidth(0); }else if (i ==lists.size()-2) { FontProve = new Font(bf, 10, Font.BOLD, BaseColor.BLACK); //cell.setBorderWidth(1); cell.disableBorderSide(14);//全没了 } else { cell.disableBorderSide(15); } cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(0, (float) 1.4); table1.addCell(cell); } table1.setSpacingAfter(40f); table1.writeSelectedRows(0, -1, signRect1.getLeft(), signRect1.getTop(), pcb1);

}else{ System.out.println(); if((i-19)%35 == 0){ System.out.println("11111111111111111111111111111111111111111111111111111111"); // 第二个表单 stamper2.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 stamper2.close(); readers=new PdfReader(templatePaths); boss = new ByteArrayOutputStream(); stamper2 = new PdfStamper(readers, boss);

pdfList.add(readers); bossList.add(boss);

form2 = stamper2.getAcroFields(); pageNo2 = form2.getFieldPositions(key).get(0).page; pcb2 = stamper2.getOverContent(pageNo2); signRect2 = form2.getFieldPositions(key).get(0).position; //表格位置 column2 = 5;

table2 = new PdfPTable(column2); tatalWidth2 = signRect2.getRight() - signRect2.getLeft() - 1;

table2.setTotalWidth(width2); table2.setLockedWidth(true); table2.setKeepTogether(true); table2.setSplitLate(false); table2.setSplitRows(true);

List<String> listdetail = lists.get(i); for (int j = 0; j <column2; j++) { Paragraph paragraph = new Paragraph(String.valueOf(listdetail.get(j)), FontProve); PdfPCell cell = new PdfPCell(paragraph); if (i == lists.size()-1) { System.out.println("i是:" + lists.size()); cell.setColspan(5); cell.setBorderWidth(0); }else if (i ==lists.size()-2) { BaseFont bftemp = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); FontProve = new Font(bftemp, 10, Font.BOLD, BaseColor.BLACK); //cell.setBorderWidth(1); cell.disableBorderSide(14);//全没了 } else { cell.disableBorderSide(15); } cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(0, (float) 1.4); table2.addCell(cell); } table2.setSpacingAfter(40f); System.out.println(signRect2.getTop()+"top"); table2.writeSelectedRows(0, -1, signRect2.getLeft(), 800, pcb2);

} //每行数据 List<String> listdetail = lists.get(i); for (int j = 0; j <column2; j++) { Paragraph paragraph = new Paragraph(String.valueOf(listdetail.get(j)), FontProve); PdfPCell cell = new PdfPCell(paragraph); if (i == lists.size()-1) { System.out.println("i是:" + lists.size()); cell.setColspan(5); cell.setBorderWidth(0); }else if (i ==lists.size()-2) { BaseFont bftemp = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); FontProve = new Font(bftemp, 10, Font.BOLD, BaseColor.BLACK); //cell.setBorderWidth(1); cell.disableBorderSide(14);//全没了 } else { cell.disableBorderSide(15); } cell.setVerticalAlignment(Element.ALIGN_CENTER); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(0, (float) 1.4); table2.addCell(cell); } table2.setSpacingAfter(40f); System.out.println(signRect2.getTop()+"top"); table2.writeSelectedRows(0, -1, signRect2.getLeft(), 800, pcb2);

}

}

Map<String, List<List<String>>> listMaps2 = (Map<String, List<List<String>>>) o.get("listss"); for (String key1 : listMaps2.keySet()) { List<List<String>> lists2 = listMaps2.get(key1); int pageNo = form2.getFieldPositions(key).get(0).page; PdfContentByte pcb = stamper2.getOverContent(pageNo); Rectangle signRect = form2.getFieldPositions(key).get(0).position; //表格位置 int column3 = lists2.get(0).size(); int row3 = lists2.size(); PdfPTable table = new PdfPTable(column3); float tatalWidth3 = signRect.getRight() - signRect.getLeft() - 1; System.out.println(tatalWidth3); int size3 = lists2.get(0).size(); float width3[] = new float[size3]; for(int i=0;i<size3;i++){ if(i==0){ width3[i]=100f; }else{ width3[i]=(tatalWidth3-60)/(size3-1); } } table.setTotalWidth(width3); table.setLockedWidth(true); table.setKeepTogether(true); table.setSplitLate(false); table.setSplitRows(true); Font FontProve3 = new Font(bf, 8, Font.BOLD,BaseColor.BLACK); //表格数据填写 for(int i=0;i<row3;i++){ List<String> list = lists2.get(i); for(int j=0;j<column3;j++){ Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve); PdfPCell cell = new PdfPCell(paragraph); cell.disableBorderSide(14);//全没了 if(i==0){ BaseFont bftemp = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); FontProve = new Font(bftemp, 5, Font.NORMAL, BaseColor.BLACK); cell.disableBorderSide(14);//全没了 }else if(i==(row3-1)){ cell.disableBorderSide(15); }else{ cell.disableBorderSide(15); }

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(), 40, pcb); } stamper2.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 stamper2.close();

}

// foot Map<String, List<List<String>>> listMaps = (Map<String, List<List<String>>>) o.get("listss"); for (String key : listMaps.keySet()) { List<List<String>> lists = listMaps.get(key); System.out.println("lists"+lists); 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(); System.out.println(column+"column"+"row"+row); PdfPTable table = new PdfPTable(column); float tatalWidth = signRect.getRight() - signRect.getLeft() - 1; System.out.println(tatalWidth); int size = lists.get(0).size(); float width[] = new float[size]; for(int i=0;i<size;i++){ if(i==0){ width[i]=100f; }else{ width[i]=(tatalWidth-60)/(size-1); } } System.out.println(width); table.setTotalWidth(width); table.setLockedWidth(true); table.setKeepTogether(true); table.setSplitLate(false); table.setSplitRows(true); Font FontProve = new Font(bf, 8, Font.BOLD,BaseColor.BLACK); //表格数据填写 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.disableBorderSide(14);//全没了 if(i==0){ BaseFont bftemp = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); FontProve = new Font(bftemp, 5, Font.NORMAL, BaseColor.BLACK); cell.disableBorderSide(14);//全没了 }else if(i==(row-1)){ cell.disableBorderSide(15); }else{ cell.disableBorderSide(15); }

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); }

stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑 stamper.close(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); System.out.println("pdfList"+pdfList.size()); if(checkSize<=19){ for(int i=0;i<1;i++){ doc.newPage(); copy.addDocument(new PdfReader(bossList.get(i).toByteArray()));

} }else{ for(int i=0;i<pdfList.size();i++){ doc.newPage(); copy.addDocument(new PdfReader(bossList.get(i).toByteArray()));

} }

doc.close();

} catch (IOException e) { System.out.println(e); } catch (DocumentException e) { System.out.println(e); }

}

注意第二个模板分页循环 stamper2 = new PdfStamper(readers, boss);之前记得进行关闭 stamper2.close();

不然会报com.itextpdf.text.exceptions.InvalidPdfException: PDF header signature not found这个错

接下来就是main方法测试了啊

public static void main(String[] args) { Map<String,String> map = new HashMap(); Map<String,String> maps = new HashMap();

map.put("invoiceNo","990696"); map.put("deliverycompany","湖南省长沙市芙蓉区"); map.put("inviocecompany","湖南省长沙市雨花区"); map.put("paymethod","支付宝"); map.put("deliverymethod","邮寄"); map.put("deliverymethod","邮寄"); map.put("forwarder","申通快递"); map.put("deliverydate","2019-9-19"); map.put("orderReference","百度一下,你就知道"); map.put("referenceOrderNo","R1112112222"); map.put("invoice_no","990696"); map.put("invoicedate","2019-9-20"); map.put("dudate","2019-10-20"); map.put("companyNo","224542"); map.put("invoicetotal","230"); map.put("companyName","XXXX有限公司"); map.put("tel","电话 12345678 "+"—"+"传真 0215");

Map<String,String> map2 = new HashMap(); // map2.put("img","C:/Users/pc/Desktop/timg.jpg");

List<List<String>> List = new ArrayList<List<String>>(); for(int i=0;i<=80;i++){ List<String> list = new ArrayList<String>(); list.add("22454223"); list.add("该产品非常好"+i); list.add("200"); list.add("23"); list.add("460"); List.add(list); }

List<String> list11 = new ArrayList<String>(); list11.add(" "); list11.add(" "); list11.add(" "); list11.add("总价"); list11.add("630");

List<String> list12 = new ArrayList<String>(); list12.add(" "); list12.add(" "); list12.add(" "); list12.add(" "); list12.add("订单交付后,如有任何问题,请在7天内与我们联系,否则,我们将不受理任何索赔."); List.add(list11); List.add(list12);

Map<String, List<List<String>>> listMap = new HashMap<String, List<List<String>>>(); listMap.put("eventList", List);

List<List<String>> ListAddress = new ArrayList<List<String>>(); List<String> listdd = new ArrayList<String>(); listdd.add("上海浦东新区"); List<String> listss = new ArrayList<String>(); listss.add("上海浦东新区华夏路"); ListAddress.add(listdd); ListAddress.add(listss); Map<String, List<List<String>>> listMaps = new HashMap<String, List<List<String>>>(); listMaps.put("companyAdress",ListAddress );

Map<String,Object> o=new HashMap(); o.put("datemap",map); // o.put("imgmap",map2); o.put("list",listMap); o.put("listss",listMaps); String uid=CommonUtils.uuid(); System.out.println(uid+"uid"); String newPDFPath ="C:/Users/pc/Desktop/"+uid+".pdf"; pdfout(o,newPDFPath);

}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 请你解释一下什么是线程池(thread pool)?

    在面向对象编程中,创建和销毁对象是很费时间的,因为创建一个对象要获取内存资源或者其它更多资源。在Java中更是如此,虚拟机将试图跟踪每一个对象,以便能够在对象销...

    剑走天涯
  • 从头到尾说一次 Java 垃圾回收,写得非常好!

    之前上学的时候有这个一个梗,说在食堂里吃饭,吃完把餐盘端走清理的,是 C++ 程序员,吃完直接就走的,是 Java 程序员。?

    Java技术栈
  • 一起学Rust-实战leetcode(三)

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。

    江湖安得便相忘
  • 什么是 Java 对象深拷贝?面试必问!

    浅拷贝只是拷贝了源对象的地址,所以源对象的值发生变化时,拷贝对象的值也会发生变化。

    Java技术栈
  • Java虚拟机最多支持多少个线程?

    McGovernTheory在StackOverflow提了这样一个问题:Java虚拟机最多支持多少个线程?跟虚拟机开发商有关么?跟操作系统呢?还有其他的因素吗...

    Java技术栈
  • 一种非大小排序(先后关系排序)—拓扑排序

    在以前很多人可能听过拓扑排序,但可能认为它太难而不愿接触学习,也不清楚是排啥序的,然而拓扑排序实际很简单,生活中也很常用,面试笔试也会遇到,所以掌握拓扑排序已是...

    全菜工程师小辉
  • AsyncContext异步请求的用法

    在Servlet 3.0中,在ServletRequest上提供了startAsync()方法

    全菜工程师小辉
  • 这个中秋,我用 Java 画了一个月饼!

    今年中秋节,我又想写点不一样的来给大家祝福,用 Java 来画一个月饼,听起来是不是很好玩?

    Java技术栈
  • 「Java Grammar」:运算符

    计算机自打诞生以来,用作最多的就是进行计算,而计算离不开运算符,所以运算符在我们的Java语言中的地位举足轻重,我们现在就来了解一下Java给我们提供的运算符。

    Vi的技术博客
  • Java 中的 T,E,K,V, 别傻傻分不清楚!

    https://juejin.im/post/5d5789d26fb9a06ad0056bd9

    Java技术栈

扫码关注云+社区

领取腾讯云代金券