I am needing to the get the rendered output of Spring 3.1 MVC View into a String (for sending to a PDF converter, or to a MIME email, etc...) and I have been using the following code:
This is injected into the Controller
@Autowired
TilesViewResolver viewResolver;
And the following helper method:
private String renderViewToString(ModelMap map, HttpServletRequest request, HttpServletResponse httpServletResponse, final String viewName) {
final StringWriter html = new StringWriter();
View pdfView = new View() {
@Override
public String getContentType() {
return "application/pdf";
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(response) {
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(html);
}
};
View realView = viewResolver.resolveViewName(viewName, Locale.US);
Map<String, Object> newModel = new HashMap<String, Object>(model);
newModel.put("pdfMode", Boolean.TRUE);
realView.render(newModel, request, wrapper);
}
};
try {
pdfView.render(map, request, httpServletResponse);
} catch (Exception e) {
// Ignored for now
}
return html.toString();
}
Credit to Ted Young and his HTML2PDFViewResolver from which my code is based on.
My Question is there a better way to do this? The code I have works fine but now I am getting close to Production and I thought that if there is room for improvement I would like to try it.
Thanks to all
You are breaking the MVC pattern by clubbing together the view and controller. A better solution is to define a view and register it to ContentNegotiatingViewResolver. Based on the content type requested the resolver would delegate the request to your view.
e.g.
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="0" />
<property name="mediaTypes">
<map>
<entry key="pdf" value="application/pdf" />
</map>
</property>
<property name="defaultViews">
<list>
<bean class="com.abc.MyCustomView">
<property name="contentType" value="pdf" />
</bean>
</list>
</property>
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With