10
我需要將Spring 3.1 MVC視圖的呈現輸出轉換爲字符串(用於發送到PDF轉換器或MIME電子郵件等)和我一直在使用下面的代碼:獲取Spring 3.1 MVC視圖的呈現輸出
這被注入控制器
@Autowired
TilesViewResolver viewResolver;
而下面的輔助方法:
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();
}
感謝Ted Young和他的HTML2PDFViewResolver從中我的代碼是基於。
我的問題是否有更好的方法來做到這一點?我的代碼工作正常,但現在我接近生產,我認爲如果有改進的空間,我想嘗試一下。
感謝所有
不好,看起來不錯。 – 2014-05-08 08:30:22
你問這是一個問題......我將它看作是一個答案......正是我所期待的......對我來說絕對有用,因爲我只需要html將它作爲我的JSON響應的一部分發送出去......豎起大拇指......你搖滾! – CodeBurner 2016-07-19 07:29:02