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。

  • 相关阅读:
    django.template.exceptions.TemplateDoesNotExist: login.html 错误处理
    pycharm 如何进行全部搜索
    python调用 sshpass
    sshpass 使用方法
    ssh 绕过The authenticity of host '*.*.*.*' can't be established 直接输入密码
    Django深入----django.db.transaction
    django深入----django.db.transaction
    Flask+ Angularjs 实例: 创建博客
    Python --写excel
    Python --链接Mongodb
  • 原文地址:https://www.cnblogs.com/rain144576/p/12903026.html
Copyright © 2011-2022 走看看