zoukankan      html  css  js  c++  java
  • 后端——框架——视图层框架——spring_mvc——《官网》阅读笔记——第一章节18(核心对象,视图解析器,PDF)

    1、概念

      在使用PDF时,此时的返回值不再是viewName,而是PdfView对象。

      PdfView是自定义类名,它必须实现AbstractPdfView接口的实现类,接口有buildPdfDocument方法,它基于itext框架。所以在开始之前需要引入itext相关jar包。

    <dependency>
    	<groupId>com.lowagie</groupId>
    	<artifactId>itext</artifactId>
    	<version>2.1.7</version>
    </dependency>
    <dependency>
    	<groupId>com.itextpdf</groupId>
    	<artifactId>itextpdf</artifactId>
    	<version>5.5.9</version>
    </dependency>
    

    2、使用

      第一步,编写PdfView(名字随意)对象实现AbstactPdfView接口,实现buildPdfDocument方法。

      第二步,注册pdfView,在视图解析器的方法中,调用registry的enableContentNegotiation方法

      第三步,handler方法直接返回PdfView对象,不是字符串(重点)

    3、示例

      Pdf类似,下面以PDF为例。实现的步骤如下:

      1、编写PdfView(自定义名称)实现AbstractPdfView接口,实现buildPdfDocument方法。下述示例中添加了表头,First Name,Last Name,Email三列。

    public class PdfView extends AbstractPdfView {
    	@Override
    	protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
    			HttpServletRequest request, HttpServletResponse response) throws Exception {
    		PdfPTable table = new PdfPTable(3);
    	table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    	table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
    		table.addCell("First Name");
    		table.addCell("Last Name");
    		table.addCell("Email");
    		document.add(table);
    	}
    }
    

      2、注册PdfView,调用registry的enableContentNegotiation方法

    registry.enableContentNegotiation(new PdfView());
    

      3、编写Handler方法,它的返回值是PdfView

    	@GetMapping("test/pdf")
    	public PdfView testPdfView()
    	{
    		ModelAndView model = new ModelAndView();
    		List<String> wordList = Arrays.asList(new String[] {"第一行","第二行","第三行"});
    		model.addObject("wordList", wordList);
    		PdfView  pdf = new PdfView();
    		return pdf;
    	}
    

      除上述方式之外,可以向response对象中写输出流,并指定类型为application/pdf。

  • 相关阅读:
    Spring和Mybatis整合
    Spring的基本操作
    mybatis在xml文件中处理特殊符号(如:大于号小于号等的方法)
    配置MyBatis 环境
    iframe元素內嵌页面如何去掉继承的html及body背景色/背景图片
    如何解决include包含页面的乱码问题
    Servlet重定向后,页面混乱的解决办法
    使用Ajax验证邮箱是否存在
    使用监听器监听用户访问页面的次数
    基于arduino的红外传感系统
  • 原文地址:https://www.cnblogs.com/rain144576/p/12903026.html
Copyright © 2011-2022 走看看