一:导入jar<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.3</version></dependency><!-- https://mvnrepository.com/artifact/itext/itext --><dependency> <groupId>itext</groupId> <artifactId>itext</artifactId> <version>1.3</version></dependency>
二:使用Adobe Acrobat DC 编辑模板
三:编写代码
/** * * @param o 写入的数据 * @param out 自定义保存pdf的文件流 * @param templatePath pdf模板路径 */ // 利用模板生成pdf public void fillTemplate(Map<String,Object> o,ServletOutputStream out,String templatePath) { PdfReader reader; ByteArrayOutputStream bos; PdfStamper stamper; try { BaseFont bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1" , BaseFont.IDENTITY_H, BaseFont.EMBEDDED); Font FontChinese = new Font(bf, 2, Font.NORMAL); reader = new PdfReader(templatePath);// 读取pdf模板 bos = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, bos); AcroFields form = stamper.getAcroFields(); java.util.Iterator<String> it = form.getFields().keySet().iterator(); form.addSubstitutionFont(bf); while (it.hasNext()) { String name = it.next().toString(); String value = o.get(name)!=null?o.get(name).toString():null; form.setField(name,value); } stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑,一定要设为true stamper.close(); Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); copy.addPage(importPage); doc.close(); } catch (IOException e) { System.out.println(e); } catch (DocumentException e) { System.out.println(e); } }}
controller调用
public String xxxController(HttpServletResponse response){//常见map集合 Map<String,Object> map = new HashMap<>(); map.put("name","名字"); /*// 设置response参数,可以打开下载页面 response.reset(); response.setCharacterEncoding("UTF-8"); // 定义输出类型 response.setContentType("application/PDF;charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + "assessment.pdf");*/ try { ServletOutputStream out = response.getOutputStream(); PdfUtil pdf = new PdfUtil();//src/main/resources/static/swagger/images/msgh.pdf 模板路径记得更换自己的,我放在项目里面了 pdf.fillTemplate(map ,out,"src/main/resources/static/swagger/images/msgh.pdf"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null;}