我正在关注Spring入门教程,并且在如何做一些相对简单的事情上不知所措,例如访问同一Controller中另一条路径的结果.
我正在尝试做的是:
>将填充的Thymeleaf模板作为HTML返回到浏览器<-此
开箱即用
>返回与pdf相同的页面
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",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
}