1、下载Adobe Acrobat DC工具来制作pdf的模板
打开一个pdf
2、制作pdf模板
把自动生成的文本框删除
然后 拖入文本框并自定义键
导入maven 依赖
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.5</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
1 @Controller 2 public class PdfView { 3 4 @RequestMapping("/pdfView/{id}") 5 public void fillTemplate(HttpServletResponse response,@PathVariable("id") Integer id) { 6 System.out.println(id); 7 // 模板路径 8 String templatePath = "E:\print\moban\ylmoban.pdf"; 9 // 生成的新文件路径 10 String newPDFPath = "E:\print\测试11.pdf"; 11 PdfReader reader; 12 FileOutputStream out; 13 ByteArrayOutputStream bos; 14 PdfStamper stamper; 15 int page=1; 16 List<PdfReader> list = new ArrayList(); 17 try { 18 //for(int i=0;i<19;i++){ 19 reader = new PdfReader(templatePath); 20 PdfReader pdfReader = null; 21 bos = new ByteArrayOutputStream(); 22 stamper = new PdfStamper(reader, bos); 23 AcroFields form = stamper.getAcroFields();
//这个form就是pdf里面的表单key就是pdf的键 value 就是往里面要放的值 24 form.setField("test1","张三"); 25 form.setField("test2","总经理"); 26 form.setField("test4","德信养老院"); 27 form.setField("test5","其它"); 28 29 //true代表生成的PDF文件不可编辑 30 stamper.setFormFlattening(true); 31 stamper.close(); 32 pdfReader = new PdfReader(bos.toByteArray()); 33 list.add(pdfReader); 34 35 //} 36 // out = new FileOutputStream(newPDFPath); 37 ServletOutputStream outputStream = response.getOutputStream(); 38 39 Document doc = new Document(); 40 PdfCopy copy = new PdfCopy(doc, outputStream); 41 doc.open(); 42 for (int k = 0; k < list.size(); k++) { 43 PdfReader pdfReader1 = list.get(k); 44 doc.newPage(); 45 copy.addDocument(pdfReader1); 46 } 47 copy.close(); 48 // PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1); 49 // copy.addPage(importPage); 50 // doc.close(); 51 } catch (Exception e) { 52 e.printStackTrace(); 53 } 54 55 } 56 public static void main(String[] args) { 57 //fillTemplate(); 58 }
这样直接访问这个controller 就可以直接生成打印预览