Spring MVC and PDF file via AbstractPdfView

Spring MVC comes with AbstractPdfView class to export data to pdf file via Bruno Lowagie’s iText library. In this tutorial, it show the use of AbstractPdfView class in Spring MVC application to export data to pdf file for download.

1. iText

Get the iText library to generate the pdf file.

    <!-- Pdf library --> 
    <dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>2.1.7</version>
    </dependency>

2. Controller

A controller class, generate dummy data for demonstration, and get the request parameter to determine which view to return. If the request parameter is equal to “PDF“, then return an Pdf view (AbstractPdfView).

File : RevenueReportController.java

package com.mkyong.common.controller;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class RevenueReportController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        String output =
            ServletRequestUtils.getStringParameter(request, "output");

        //dummy data
        Map<String,String> revenueData = new HashMap<String,String>();
        revenueData.put("1/20/2010", "$100,000");
        revenueData.put("1/21/2010", "$200,000");
        revenueData.put("1/22/2010", "$300,000");
        revenueData.put("1/23/2010", "$400,000");
        revenueData.put("1/24/2010", "$500,000");

        if(output ==null || "".equals(output)){
            //return normal view
            return new ModelAndView("RevenueSummary","revenueData",revenueData);

        }else if("PDF".equals(output.toUpperCase())){
            //return excel view
            return new ModelAndView("PdfRevenueSummary","revenueData",revenueData);

        }else{
            //return normal view
            return new ModelAndView("RevenueSummary","revenueData",revenueData);

        }   
    }   
}

3. PdfRevenueReportView

Create a pdf view by extends the AbstractPdfView class, override the buildExcelDocument() method to populate the data to pdf file. The AbstractPdfView is using the iText API to generate the pdf file.

File : PdfRevenueReportView.java

package com.mkyong.common.view;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;

public class PdfRevenueReportView extends AbstractPdfView{

    @Override
    protected void buildPdfDocument(Map model, Document document,
        PdfWriter writer, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");

        Table table = new Table(2);
        table.addCell("Month");
        table.addCell("Revenue");

        for (Map.Entry<String, String> entry : revenueData.entrySet()) {
            table.addCell(entry.getKey());
            table.addCell(entry.getValue());
                }

        document.add(table);
    }
}

4. Spring Configuration

Create a XmlViewResolver for the Pdf view.

<beans ...>

 <bean 
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

    <bean class="com.mkyong.common.controller.RevenueReportController" />

    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="location">
          <value>/WEB-INF/spring-pdf-views.xml</value>
       </property>
    </bean>

</beans>

File : spring-pdf-views.xml

<beans ...">

   <bean id="PdfRevenueSummary"
    class="com.mkyong.common.view.PdfRevenueReportView">
   </bean>

</beans>

5. Demo

URL : http://localhost:8080/SpringMVC/revenuereport.htm?output=pdf

It generates a pdf file for user to download.

SpringMVC-PDF-Example

### Android MVC Framework Usage and Examples In the context of developing applications on the Android platform using an MVC (Model-View-Controller) architecture, it's important to understand how each component interacts within this design pattern. Unlike frameworks such as Spring MVC which operates under Java-based web environments[^2], Android developers must adapt these principles specifically for mobile application development. #### Model Component The model represents data structures or business logic used throughout your app. For example, consider a simple note-taking application where notes are stored locally via SQLite database: ```java public class Note { private long id; private String title; private String content; public Note(long id, String title, String content){ this.id = id; this.title = title; this.content = content; } // Getters & Setters... } ``` This `Note` object serves as part of the model layer responsible for handling information about individual notes. #### View Component Views represent what users see when interacting with apps built upon MVC patterns. In Android, views can be implemented through XML layouts combined with activities/fragments that inflate those resources at runtime. Here’s an excerpt from a layout file named `activity_main.xml`: ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/title_edit_text" android:hint="Enter Title" android:inputType="textCapSentences" android:layout_width="match_parent" android:layout_height="wrap_content"/> <!-- More UI elements --> </LinearLayout> ``` Such code defines visual components like text fields but doesn't contain any direct interaction logic beyond defining their appearance properties. #### Controller Component Controllers act as intermediaries between models and views; they handle user inputs while updating relevant parts accordingly based on changes made either internally or externally. Within Android projects following MVC practices, Activities often play dual roles acting both as controllers managing lifecycle events alongside serving presentation purposes too. Below demonstrates basic event handling inside MainActivity.java: ```java import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.save_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editTextTitle = findViewById(R.id.title_edit_text); String newTitle = editTextTitle.getText().toString(); // Assuming there exists some method addNewNote(String) DatabaseHelper.getInstance(MainActivity.this).addNewNote(newTitle,""); } }); } } ``` Here, clicking save button triggers adding a newly created note into storage managed by `DatabaseHelper`. While not explicitly mentioned in provided references, adapting concepts similar to those found within server-side implementations like Spring MVC helps structure robust client-side software solutions effectively even outside traditional desktop/web contexts.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值