Java thymeleaf html 模板导出PDF

pom文件
<flying-saucer-pdf.version>9.1.18</flying-saucer-pdf.version> <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>

 <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>flying-saucer-pdf</artifactId>
            <version>${flying-saucer-pdf.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>

pdfutils

package com.ys.utils;

import com.lowagie.text.pdf.BaseFont;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PdfUtils {

    public static void method() throws Exception{
//        String path = request.getSession().getServletContext().getRealPath("");
//        String filePath = path + env.getProperty("outputPath") + File.separator + UUIDUtil.getShortUuid() + ".pdf";
        OutputStream out = new FileOutputStream(new File("F:/sss.pdf"));
        Map<String, Object> locker = new HashMap<>();
        locker.put("lockerName", "lockerName");
        locker.put("exportDate", "exportDate");
        locker.put("paymentModeName", "paymentModeName");
        locker.put("paymentMothod", "paymentMothod");
        locker.put("paymentTotal", "paymentTotal");
        locker.put("boxSizeName", "boxSizeName");
        locker.put("boxSize", "boxSize");
        locker.put("boxSizeTotal", "boxSizeTotal");
        locker.put("locationName", "locationName");
        locker.put("location", "location");
        locker.put("locationTotal", "locationTotal");
        Map<String, Object> paymentList = new HashMap<>();
        List<Map> list = new ArrayList<>();
        paymentList.put("paymentMothod", "Alipay");
        paymentList.put("paymentTotal", 90.0);
        list.add(paymentList);
        Map<String, Object> boxSizeList = new HashMap<>();

        List<Map> boxlist = new ArrayList<>();
        boxSizeList.put("boxSize", "smaller");
        boxSizeList.put("boxSizeTotal", 30.0);
        boxlist.add(boxSizeList);
        Map<String, Object> locationList = new HashMap<>();

        List<Map> locationlist = new ArrayList<>();
        locationList.put("location", "New york");
        locationList.put("locationTotal", 20.0);
        locationlist.add(locationList);
        Map<String, Object> map = new HashMap<>();
        map.put("locker", locker);
        map.put("paymentList", list);
        map.put("boxSizeList", boxlist);
        map.put("locationList", locationlist);
//        String fileTemplatePath = path + env.getProperty("templatePath") + File.separator;
        String htmlStr = generate("F:/project/sourceysProject/pdfModel/", "LockerModel", map);

        DocumentBuilder builder =  DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("UTF-8")));
        ITextRenderer renderer = new ITextRenderer();

        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont("F:/project/sourceysProject/pdfModel/simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//        fontResolver.addFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        renderer.setDocument(doc, null);
        renderer.layout();
        renderer.createPDF(out);
        out.close();
        // 下载文件
        String fileName = "test.pdf";
//        ExcelUtil.downloadFile(request, response, fileName, filePath);
    }

    public static String generate(String filePath, String template, Map<String, Object> variables) throws Exception{

        //创建模板解析器
        FileTemplateResolver templateResolver = new FileTemplateResolver();
        templateResolver.setPrefix(filePath);
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setCacheTTLMs(Long.valueOf(3600000L));
        templateResolver.setCacheable(true);

        //创建模板引擎并初始化解析器
        TemplateEngine engine = new TemplateEngine();
        engine.setTemplateResolver(templateResolver);
        engine.isInitialized();

        //输出流
        StringWriter stringWriter = new StringWriter();
        BufferedWriter writer = new BufferedWriter(stringWriter);

        //获取上下文
        Context ctx = new Context();
        ctx.setVariables(variables);
        engine.process(template,  ctx, writer);

        stringWriter.flush();
        stringWriter.close();
        writer.flush();
        writer.close();

        //输出html
        String htmlStr = stringWriter.toString();
        return htmlStr;
    }

    public static void main(String args[]) throws Exception {
          method();
//        String Str = generate("d:\\","test",new HashMap<String, Object>());
//        System.out.println(Str);
    }
}

html模板

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf!!!!!</title>
    <meta http-equiv="Content-Type" content="text/html;" charset="UTF-8"/>
    <style type="text/css">
        @page {
            size: 210mm 297mm; /*设置纸张大小:A4(210mm 297mm)、A3(297mm 420mm) 横向则反过来*/
            margin: 0.25in;
            padding: 1em;
            @bottom-center{
                content:"";
                font-family: SimSun;
                font-size: 12px;
                color: red;
            };
            @top-center { content: element(header) };
            @bottom-right{
                content:"第" counter(page) "页  共 " counter(pages) "页";
                font-family: SimSun;
                font-size: 12px;
                color:#000;
            };
        }

        body {
            font-family: 'SimSun'
        }
        h2 {
            color: #0C0C0C;
        }
        table, th, td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
            font-size: 12px;
            color: #0C0C0C;
        }
    </style>
</head>
<body>
<div style="text-align: center;"><h2 th:text="${locker.lockerName}"></h2></div>
<table>
    <tbody>
    <tr>
        <td colspan="10" style="background-color: #FFFF99; text-align: left; width: 190mm" th:text="${locker.exportDate}"></td>
    </tr>
    <tr>
        <td colspan="10" style="background-color: #FFFF99; text-align: left" th:text="${locker.paymentModeName}"></td>
    </tr>
    <tr>
        <th colspan="5" th:text="${locker.paymentMothod}"></th>
        <th colspan="5" th:text="${locker.paymentTotal}"></th>
    </tr>
    <tr th:each="cabinet:${paymentList}">
        <th colspan="5" th:text="${cabinet.paymentMothod}"></th>
        <th colspan="5" th:text="${cabinet.paymentTotal}"></th>
    </tr>
    <tr>
        <td colspan="10" style="background-color: #FFFF99; text-align: left" th:text="${locker.boxSizeName}"></td>
    </tr>
    <tr>
        <th colspan="5" th:text="${locker.boxSize}"></th>
        <th colspan="5" th:text="${locker.boxSizeTotal}"></th>
    </tr>
    <tr th:each="boxSize:${boxSizeList}">
        <th colspan="5" th:text="${boxSize.boxSize}"></th>
        <th colspan="5" th:text="${boxSize.boxSizeTotal}"></th>
    </tr>
    <tr>
        <td colspan="10" style="background-color: #FFFF99; text-align: left" th:text="${locker.locationName}"></td>
    </tr>
    <tr>
        <th colspan="5" th:text="${locker.location}"></th>
        <th colspan="5" th:text="${locker.locationTotal}"></th>
    </tr>
    <tr th:each="location:${locationList}">
        <th colspan="5" th:text="${location.location}"></th>
        <th colspan="5" th:text="${location.locationTotal}"></th>
    </tr>
    </tbody>
</table>
</body>
</html>
Java中,如果你需要将数据导出PDF并适用于服务器环境,通常会使用一些成熟的库来帮助完成这项任务,如iText、Apache PDFBox或者是Thymeleaf + FreeMarker等模板引擎结合PDFWriter。以下是一个简化的步骤: 1. 引入依赖:对于iText,你需要在项目中添加iText库的依赖;如果是FreeMarker,还要引入freemarker和itextpdf。 ```xml <!-- iText --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> <!-- Thymeleaf and Apache PDFBox --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.24</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.14.RELEASE</version> </dependency> ``` 2. 编写模板:使用ThymeleafHTML+Dialect)或FreeMarker编写动态内容的HTML模板,包含变量标签用于插入数据。 3. 配置数据模型:创建Java对象,将要导出的数据填充到这个对象中。 4. 创建PDF:使用模板渲染数据,并将其转换为PDF。例如,使用iText可以先生成HTML然后转换,或者直接在PDF上操作。 ```java // 使用iText Document document = new Document(); try (OutputStream os = response.getOutputStream()) { PdfWriter.getInstance(document, os); document.open(); // 使用模板和数据填充PDF PdfPTable table = new PdfPTable(...); // 根据模板创建表格 table.addCell("Data"); // 插入数据 document.add(table); document.close(); } // 或者使用Thymeleaf和Apache PDFBox Template template = engine.process("template.html", model); try (OutputStream out = response.getOutputStream()) { PdfCopy copy = new PdfCopy(out, new Document()); copy.copyPage(template.getOriginal()); // 渲染并写入PDF PdfStamper stamper = new PdfStamper(copy, new File(...)); stamper.getOverContent(1).addTemplate(template); } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值