Spring 的 AbstractPdfStamperView 和 iText 可用于使用预定义模板生成 PDF。
package com.pdf.view;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.web.servlet.view.document.AbstractPdfStamperView;
import com.lowagie.text.pdf.PdfStamper;
public class PDFView extends AbstractPdfStamperView implements
MessageSourceAware {
private MessageSource messageSource;
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
protected void mergePdfDocument(Map<String, Object> model,
PdfStamper stamper, HttpServletRequest request,
HttpServletResponse response) throws Exception {
stamper.setFormFlattening(true);
String customerName = (String) model.get("customerName");
Locale locale = request.getLocale();
stamper.getAcroFields().setField("customerNameLabel",
messageSource.getMessage("label.customername", null, locale));
stamper.getAcroFields().setField("customerNameValue", customerName);
stamper.close();
}
}
我使用了 XMLViewResolver。下面是 spring-servlet.xml 中的条目:
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-pdf-views.xml</value>
</property>
</bean>
下面是 spring-pdf-views.xml 的内容
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="invoicePDF"
class="com.pdf.view.PDFView">
<property name="url" value = "/WEB-INF/resources/templates/invoiceTemplate.pdf" />
</bean>
</beans>
下面是控制器代码中定义的方法,它将呈现视图。此处 ModelAndView 中设置的视图名称与上面 spring-pdf-views.xml 中定义的相同。
@RequestMapping(value = "/pdf",method = RequestMethod.POST)
public ModelAndView renderPDF(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("invoicePDF");
mav.addObject("customerName", "XYZ");
return mav;
}