📅  最后修改于: 2020-11-11 06:37:02             🧑  作者: Mango
以下示例显示了如何使用Spring Web MVC Framework生成PDF。首先,让我们拥有一个可用的Eclipse IDE,并遵循以下步骤来使用Spring Web Framework开发基于动态表单的Web应用程序。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. |
2 | Create Java classes UserPDFView and PDFController under the com.tutorialspoint package. |
3 | Download the iText library − iText from the maven repository page. Put it in your CLASSPATH. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class PDFController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map userData = new HashMap();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
package com.tutorialspoint;
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 UserPDFView extends AbstractPdfView {
protected void buildPdfDocument(Map model, Document document,
PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map userData = (Map) model.get("userData");
Table table = new Table(2);
table.addCell("Roll No");
table.addCell("Name");
for (Map.Entry entry : userData.entrySet()) {
table.addCell(entry.getKey());
table.addCell(entry.getValue());
}
document.add(table);
}
}
/WEB-INF/views.xml
在这里,我们创建了一个PDFController和UserPDFView。 iText库处理PDF文件格式,并将数据转换为PDF文档。
完成创建源文件和配置文件后,导出应用程序。右键单击您的应用程序,使用“导出”→“ WAR文件”选项,并将TestWeb.war文件保存在Tomcat的webapps文件夹中。
现在,启动Tomcat服务器,并确保您能够使用标准浏览器从webapps文件夹访问其他网页。我们也可以尝试以下URL- http:// localhost:8080 / TestWeb / pdf ,如果一切按计划进行,我们将看到以下屏幕。