복붙노트

[SPRING] Thymeleaf를 사용하여 Spring의 웹 기반 Scope에서 HTML 파일을 처리하고 처리 된 템플릿을 String으로 저장

SPRING

Thymeleaf를 사용하여 Spring의 웹 기반 Scope에서 HTML 파일을 처리하고 처리 된 템플릿을 String으로 저장

나는 thymeleaf를 사용하여 HTML 파일을 렌더링하려고하고 있으며 웹 기반 범위 인 Spring 변수에서 결과 HTML 컨텐트를 유지하므로 나중에 전자 메일을 보내거나 pdf로 컨텐트를 변환 할 때 사용할 수 있습니다. 나는이 웹 사이트에서 주어진 구현을 통해 갔지만 그것이 나에게 알 수없는 오류를 주었다. 나는 spring boot 1.5.12를 사용하고있다. thymeleaf 3.0.9와 함께 릴리스한다. thymeleaf dialect 2.2.2. 아래는 나의 구현이다. 도와주세요.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

@Controller
public class jataController {

    @GetMapping(value = "/manual-thym")
    @ResponseBody
    public void justSample() {
        Context context = new Context();
        String filename = "templates/view/failure";
        String html = renderHtml(filename, context);
        System.out.println("template\n" + html);
    }

    private String renderHtml(String filename, Context context) {

        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        templateResolver.setOrder(1);
        templateResolver.setCharacterEncoding("UTF-8");

        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);

        String html = templateEngine.process(filename, context);

        return html;
    }
}

그리고 StackTrace :

2018-04-19 12:26:43.742 ERROR 6375 --- [nio-9000-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: ognl/PropertyAccessor] with root cause

java.lang.ClassNotFoundException: ognl.PropertyAccessor
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_162]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_162]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) ~[na:1.8.0_162]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_162]
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_162]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_162]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_162]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_162]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_162]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_162]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_162]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_162]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_162]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_162]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338) ~[na:1.8.0_162]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_162]
    at org.thymeleaf.standard.expression.OGNLVariableExpressionEvaluator.<init>(OGNLVariableExpressionEvaluator.java:83) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.standard.StandardDialect.getVariableExpressionEvaluator(StandardDialect.java:179) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.standard.StandardDialect.getExecutionAttributes(StandardDialect.java:393) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.DialectSetConfiguration.build(DialectSetConfiguration.java:263) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.EngineConfiguration.<init>(EngineConfiguration.java:123) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.initialize(TemplateEngine.java:336) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1079) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1059) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1048) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE]
    at com.siqes.flight.controller.jataController.renderHtml(jataController.java:37) ~[classes/:na]
    at com.siqes.flight.controller.jataController.justSample(jataController.java:19) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_162]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_162]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_162]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_162]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) ~[spring-webmvc-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55) ~[spring-boot-1.5.12.RELEASE.jar:1.5.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:111) ~[spring-boot-actuator-1.5.12.RELEASE.jar:1.5.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106) ~[spring-boot-actuator-1.5.12.RELEASE.jar:1.5.12.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.16.RELEASE.jar:4.3.16.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) ~[tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:613) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_162]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_162]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.29.jar:8.5.29]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162]

해결법

  1. ==============================

    1.아래 업데이트보기

    아래 업데이트보기

    Thymeleaf를 설정할 때 autowire default가 사용될 때 템플릿 엔진과 템플릿 해석기를 정의해야합니다. 매번 인스턴스를 생성하는 것은 좋은 습관이 아닙니다. 여기 예제 구성 :

    @Configuration
    @EnableWebMvc
    public class ThymeleafConfiguration {
    
        @Bean
        public SpringTemplateEngine templateEngine() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.setTemplateResolver(thymeleafTemplateResolver());
            return templateEngine;
        }
    
        @Bean
        public SpringResourceTemplateResolver thymeleafTemplateResolver() {
            SpringResourceTemplateResolver templateResolver 
              = new SpringResourceTemplateResolver();
            templateResolver.setPrefix("/WEB-INF/views/");
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode("HTML5");
            return templateResolver;
        }
    }
    

    그런 다음 프로그래밍 방식으로 실험하고 싶다면 autowire 할 수는 있지만 thymeleaf로 html 페이지를 제공하는 일반적인 흐름은보기 해석기를 정의하는 것입니다.

    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }
    

    이 모든 것을 통해 컨트롤러를 다음과 같이 작성할 수 있습니다.

    @Controller
    public class MyController {
    
        @RequestMapping(value = "/test", method = RequestMethod.GET)
        public String test() {
            return "yourTemplateName";
        }
    }
    

    모델 속성을 사용하여 매개 변수를 템플릿에 전달할 수 있습니다.

    업데이트 31/07/2018

    불행히도 나는 개념 증명을 완성 할 시간이 없다. 그러나 아래 코드가 그 흐름을 보여주기에 충분하다고 생각한다. 실행하고 localhost : 8080 / test를 호출하면 콘솔에서 출력 html을 볼 수 있습니다. pdf 생성은 뷰 확인자로 추가되거나 프로그래밍 방식으로 호출 될 수 있습니다.이 예제에서는 xhtmlrenderer를 사용합니다. 나는 그것을 끝내야 할 시간이 없으므로 주석을 달았지만 핵심은 템플릿 엔진을 autowiring하여 html 및 pdf 생성을 제공하는 서비스입니다.

    Pom.hml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.github.paizo</groupId>
        <artifactId>html2pdf</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>html2pdf</name>
        <description>Demo project for Spring Boot</description>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.3.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.xhtmlrenderer</groupId>
                <artifactId>flying-saucer-pdf</artifactId>
                <version>9.1.14</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    
    </project>
    

    ThymeleafConfiguration.java

    @Configuration
    public class ThymeleafConfiguration {
    
        @Bean
        public SpringTemplateEngine templateEngine() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.setTemplateResolver(thymeleafTemplateResolver());
            return templateEngine;
        }
    
        @Bean
        public ClassLoaderTemplateResolver thymeleafTemplateResolver() {
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            templateResolver.setPrefix("templates/");
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode("HTML5");
            return templateResolver;
        }
    }
    

    HelloWorldController.java

    @Controller
    public class HelloWorldController {
    
        @Autowired
        private Html2PdfService pdfService;
    
        @GetMapping(path = "/test")
        public String hello() {
            Map parameters = new HashMap();
            parameters.put("name", "Borat");
            System.out.println(pdfService.template2Html("test", parameters));
            return "test";
        }
    
    //    @ResponseBody
    //    @GetMapping
    //    public ResponseEntity helloPdf() {
    //        Map parameters = new HashMap();
    //        parameters.put("name", "Borat");
    //        pdfService.template2Pdf("test", parameters);
    //        String filePath = "PATH_HERE";
    //        InputStream inputStream = new FileInputStream(new File(filePath));
    //        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
    //        HttpHeaders headers = new HttpHeaders();
    //        headers.setContentLength();
    //        return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);
    //    }
    }
    

    Html2PdfService.java

    @Service
    public class Html2PdfService {
    
        @Autowired
        private TemplateEngine templateEngine;
    
        public OutputStream template2Pdf(String templateName, Map parameters) {
    //        OutputStream outputStream = new BufferedOutputStream();
    //        IOUtils.copy()
    //
    //        Context ctx = new Context();
    //        String processedHtml = templateEngine.process(templateName, ctx);
    //        ITextRenderer renderer = new ITextRenderer();
    //        renderer.setDocumentFromString(processedHtml);
    //        renderer.layout();
    //        renderer.createPDF(os, false);
    //        renderer.finishPDF();
            return null;
        }
    
        public String template2Html(String templateName, Map parameters) {
            Context ctx = new Context();
            ctx.setVariable("name", "pippo");
            String processedHtml = templateEngine.process(templateName, ctx);
            return processedHtml;
        }
    }
    

    Html2pdfApplication.java

    @SpringBootApplication
    public class Html2pdfApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(Html2pdfApplication.class, args);
        }
    }
    

    만약 당신이 즉시 pdf 파일을 생성하고 바이트 배열이나 임시 파일이 아닌 스트림을 사용하는 것이 좋습니다 컨트롤러에서 응답으로 제공 할 계획이다.

  2. ==============================

    2.비슷한 Springboot와 Thymeleaf 버전을 사용하고 있는데, 몇 가지 프로젝트에서 나에게 도움이되었다.

    비슷한 Springboot와 Thymeleaf 버전을 사용하고 있는데, 몇 가지 프로젝트에서 나에게 도움이되었다.

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    @Component
    public class EmailProcessor {
    
        private TemplateEngine htmlTemplateEngine;
    
        @Autowired
        public EmailProcessor(TemplateEngine templateEngine) {
            this.htmlTemplateEngine = templateEngine;
        }
    
    
        public String process(User user) {
    
            final Context ctx = new Context();
    
            if (user != null) {
                ctx.setVariable("user", user);
            }
    
            return htmlTemplateEngine.process("emails/template", ctx);
        }
    }
    

    이메일 템플릿은 다음 위치에있는 일반 Thymeleaf 템플릿입니다.

  3. ==============================

    3.TemplateEngine이 singleton bean 내부에서 autowired되면, 아래에 언급 된 코드가 완벽하게 작동합니다.

    TemplateEngine이 singleton bean 내부에서 autowired되면, 아래에 언급 된 코드가 완벽하게 작동합니다.

    @Controller
    public class jataController {
    
        @Autowired
        private TemplateEngine templateEngine;
    
        @GetMapping(value = "/manual-thym")
        @ResponseBody
        public void justSample() {
            Context context = new Context();
            String filename = "templates/view/generated-ticket.html";
            String html = renderHtml(filename, context);
            System.out.println("template\n" + html);
        }
    
        private String renderHtml(String filename, Context context) {
    
            ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
            templateResolver.setSuffix(".html");
            templateResolver.setTemplateMode(TemplateMode.HTML);
            templateResolver.setCacheable(false);
            templateResolver.setOrder(1);
            templateResolver.setCharacterEncoding("UTF-8");
    
            templateEngine.setTemplateResolver(templateResolver);
    
            String html = templateEngine.process(filename, context);
    
            return html;
        }
    }
    

    TemplateEngine이 요청 범위 bean 유형에서 autowired되면 예외를 발생시키고 thymeleaf는 메모리 누수를 생성합니다. 마지막으로 수많은 히트와 시도로 @paizo에게 감사의 말을 전합니다. 몇 가지 나쁜 습관을 포함 할 수 있지만 이것이 어떻게 작동하는지입니다.

    @Controller
    @Configuration
    @EnableWebMvc
    @ApplicationScope
    public class MyThymeleafConfig {
    
        @GetMapping("/view-template")
        @ResponseBody
        public void viewTemplates() {
    
            Context context = new Context();
            context.setVariable("mydata", "this is it");
    
            String html = templateEngine().process("templates/view-to-process.html", context);
            System.out.println(html);
        }
    
    
        /*
    
        configuration for thymeleaf and template processing
    
        */
    
        @Bean
        public SpringTemplateEngine templateEngine() {
            SpringTemplateEngine templateEngine = new SpringTemplateEngine();
            templateEngine.setTemplateResolver(thymeleafTemplateResolver());
            return templateEngine;
        }
    
        @Bean
        public SpringResourceTemplateResolver thymeleafTemplateResolver() {
            SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
            templateResolver.setPrefix("classpath:");
            templateResolver.setSuffix(".html");
            templateResolver.setCacheable(false);
            templateResolver.setTemplateMode(TemplateMode.HTML);
            return templateResolver;
        }
    
        @Bean
        public ThymeleafViewResolver thymeleafViewResolver() {
            ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
            viewResolver.setTemplateEngine(templateEngine());
            return viewResolver;
        }
    }
    

    다음과 같이 다른 bean을 정의 할 정적 리소스를 제공해야합니다.

    @Configuration
    @EnableWebMvc
    public class StaticResourceConfig implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry
                    .addResourceHandler("/**")
                    .addResourceLocations("/static/", "classpath:static/");
        }
    }
    

    이 솔루션은 어떤 포럼에서도 찾을 수 없습니다. 그러나 나는 위의 코드에 대한 더 나은 구현을 제공하도록 Spring 개발자에게 요청할뿐 아니라 요청할 것이다.

  4. from https://stackoverflow.com/questions/49914891/process-html-file-using-thymeleaf-in-web-based-scopes-of-spring-and-store-the-pr by cc-by-sa and MIT license