[英]How to get HTML form data for user Object | Spring Boot | Controller |
[英]Spring Boot 2: Get html output in controller
我正在按照Spring入门教程进行操作,并且我在如何做一些应该相对简单的事情上,比如在同一个Controller中访问另一个路径的结果。
我正在尝试做什么:
GreetingController:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.thymeleaf.TemplateEngine;
@Controller
@RequestMapping(path = "/")
public class GreetingController {
@Autowired private TemplateEngine templateEngine;
@RequestMapping(value = "/index", method = RequestMethod.GET, produces = "application/html")
public String html(Model model) {
model.addAttribute("some_data", some_data.getIt());
return "some_template";
}
@RequestMapping(value = "/pdf", method = RequestMethod.GET, produces = "application/pdf")
public String pdf() {
// Option 1: get HTML output from html path
// Option 2: put the same data in some_template via the template engine and get the resulting HTML
// write HTML to a file using FileWriter
// then print the temporary file with HTML to PDF via wkhtml2pdf
return "generated_pdf";
}
}`
也许我说这一切都错了,有一个更容易的方法来获取填充的HTML,请指教。
编辑:
试图做类似事情的人的Gradle依赖关系:
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-devtools")
testCompile("org.springframework.boot:spring-boot-starter-test")
}
如果您对获取生成的HTML感兴趣,最简单的解决方案可能是使用Thymeleaf的TemplateEngine
,就像您已经做过的那样:
Context context = new Context(Locale.getDefault());
context.setVariable("some_data", someData.getIt());
String html = templateEngine.process("some_template", context);
之后,您可以使用任何HTML到PDF库来处理它。 例如,如果你正在使用Flying Saucer ,你可以写下这样的东西:
try (ServletOutputStream stream = response.getOutputStream()) {
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(stream);
renderer.finishPDF();
} catch (IOException | DocumentException ex) {
// Error handling
}
由于ITextRenderer
允许您直接写入OutputStream
,因此您可以使用HttpServletResponse.getOutputStream()
来执行此操作:
@GetMapping("/pdf")
public void pdf(HttpServletResponse response) {
// Generate HTML + PDF
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.