合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
SpringMVC 中视图的顶级接口为`View`,其顶级父类为`AbstractView`,我们可以实现`View`,或者继承`AbstractView`,或者继承`AbstractView`的子类来实现自定义视图。 :-: ![](https://img.kancloud.cn/f0/38/f0387181ed96ffdc1603a00d92f87498_1624x442.jpg) `AbstractView`部分子类 下面通过继承`AbstarctPdfView`来自定义pdf视图。步骤如下: **1. 引入itext依赖** ```xml <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> <scope>compile</scope> </dependency> ``` **2. 创建实体层** ```java @Data @AllArgsConstructor public class Student { private String name; private Integer age; private String gender; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date born; } ``` **3. 继承AbstractPdfView类创建对应的pdf视图** ```java public class StudentPdfView extends AbstractPdfView { @Override protected void buildPdfDocument(Map<String, Object> map, Document document, PdfWriter pdfWriter , HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception { PdfPTable table = new PdfPTable(4); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); table.getDefaultCell().setBackgroundColor(Color.lightGray); // 设置字体否则对中文不显示,在这里我使用本地的《楷体 常规》字体 BaseFont baseFont = BaseFont.createFont("c:/Windows/Fonts/simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont); PdfPCell pdfPCell = new PdfPCell(); pdfPCell.setPhrase(new Paragraph("名字", font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph("年龄", font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph("性别", font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph("生日", font)); table.addCell(pdfPCell); List<Student> studentList = (List<Student>) map.get("students"); for (Student student : studentList) { pdfPCell.setPhrase(new Paragraph(student.getName(), font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph(student.getAge() + "", font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph(student.getGender(), font)); table.addCell(pdfPCell); pdfPCell.setPhrase(new Paragraph(student.getBorn().toString(), font)); table.addCell(pdfPCell); } document.add(table); } } ``` **4. controller层** ```java @Controller public class StudentController { //请求地址必须以.pdf后缀 @GetMapping("/v7/pdf/student.pdf") public ModelAndView studentPdf() throws Exception { List<Student> studentList = new ArrayList<Student>(); studentList.add(new Student("张三", 25, "男", new Date())); studentList.add(new Student("李四", 29, "男", new Date())); Map<String, Object> map = new HashMap<String, Object>(1); map.put("students", studentList); StudentPdfView view = new StudentPdfView(); return new ModelAndView(view, map); } } ``` **5. 测试** 启动项目后访问 http://localhost:8080/mvc/v7/pdf/student.pdf ,将会看到如下效果。 ![](https://img.kancloud.cn/f2/8b/f28baa9ce72ab5196da8d20c774d4225_2560x527.jpg)