简体   繁体   中英

Spring Boot + Thymeleaf + Flying Saucer imported css not working

I don't understand why css is not working (I already followed what is said on this thread ) I have the following file structure for my ressources :

resources
    - static
         -style
            style.css
 - templates:
      - CV.html

In the template I verified that the URL is correctly generated, it is. The CSS is also correctly served : when I use the generated URL in the browser, the CSS file is served.

My Template code :

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" lang="fr">
<head>
    <title>CV ARSENE LAPOSTOLET</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link type="stylesheet" href="../static/css/style.css" th:href="@{|${baseUrl}/css/style.css|}"/>

</head>

<body>

<span th:text="|${baseUrl}/css/style.css|"></span>

<!--/*@thymesVar id="abilities" type="List<Ability>"*/-->
<div class="rouge" th:each="ability: ${abilities}">
    <span th:text="${ability.getName()}"></span>
</div>
</body>
</html>

My Java code :

@RestController
@RequestMapping("/cv")
@AllArgsConstructor
public class CvController {

    private CvService cvService;
    private AbilityRepository abilityRepository;
    private ServletContext servletContext;

    @GetMapping("")
    public ResponseEntity<Resource> getCv(HttpServletRequest servletRequest, HttpServletResponse servletResponse){
        Locale locale = getLocale(servletRequest);
        WebContext context = new WebContext(servletRequest, servletResponse, servletContext, locale);
        context.setVariable("abilities", abilityRepository.findAll());
        context.setVariable("baseUrl",getCurrentBaseUrl());

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("application/pdf"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + "CV_ARSENE_LAPOSTOLET.pdf" + "\"")
                .body(new ByteArrayResource(cvService.renderCv(context)));
    }

    private static String getCurrentBaseUrl() {
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = sra.getRequest();
        return req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath();
    }
}
@Service
@AllArgsConstructor
@CommonsLog
public class CvService {

    private TemplateEngine templateEngine;

    public byte[] renderCv(WebContext ctx) {

        String processedHtml = templateEngine.process("CV", ctx);

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(processedHtml);
            renderer.layout();
            renderer.createPDF(os);

            return os.toByteArray();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}

Problem

Hi i don't know if you already fixed the problem but i'll give you my solution. The same problem happened to me, i was trying to link css into html but nothing happened without any warning. This problem is related with the method call in your java code.

renderer.setDocumentFromString(processedHtml);

This method has one overload

public void setDocumentFromString(String content, String baseUrl);

as you can see it also accepts the wich is required for picking the right file.

Solution

Firstly i've generated a where my resource files are located. ,我的资源文件所在的位置。

private static void generatePdf(String html) throws Exception {
        String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf";
        OutputStream outputStream = new FileOutputStream(outputFolder);

        String baseUrl = FileSystems
                .getDefault()
                .getPath("src", "main", "resources")
                .toUri()
                .toURL()
                .toString();

        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html, baseUrl);
        renderer.layout();
        renderer.createPDF(outputStream);

        outputStream.close();
}

Secondly i've inserted the css file related to the 相关的 css 文件

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" type="text/css" media="all" href="style.css"/>
</head>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM