Spring   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java-Spring Boot 2:在控制器中获取html输出 大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在关注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,最简单的@L_675_8@案可能是使用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
}

大佬总结

以上是大佬教程为你收集整理的java-Spring Boot 2:在控制器中获取html输出 全部内容,希望文章能够帮你解决java-Spring Boot 2:在控制器中获取html输出 所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。