html 轉成pdf輸出


1,利用freemark 生成html

2,依賴

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>


        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>3.0.1</version>
        </dependency>

3,index.ftl

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>

<body>
This is my HTML page. <br>
<h1>${user}</h1>
</body>
</html>

4,代碼

  @Autowired
    private Configuration configuration;


    @GetMapping("/pdf")
    public void pdf(HttpServletResponse response) throws IOException, DocumentException, TemplateException {
        Template template = configuration.getTemplate("index.ftl");

        // 數據
        Map root = new HashMap();
        root.put("user", "Jack hui");

        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment; filename=citiesreport.pdf");
        ServletOutputStream outputStream = response.getOutputStream();

        StringWriter out = new StringWriter();
        template.process(root, out);
        String html = out.toString();
        HtmlConverter.convertToPdf(html, outputStream);
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM