加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java-Spring Boot 2:在控制器中获取html输出

发布时间:2020-12-15 01:17:57 所属栏目:大数据 来源:网络整理
导读:我正在关注Spring入门教程,并且在如何做一些相对简单的事情上不知所措,例如访问同一Controller中另一条路径的结果. 我正在尝试做的是: 将填充的Thymeleaf模板作为HTML返回到浏览器 开箱即用 返回与pdf相同的页面 GreetingController: import org.springfra

我正在关注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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读