SpringBoot implements freemarker filling in ftl format and converting to Word and PDF

gradle dependencies:

 implementation 'org.freemarker:freemarker:2.3.31'
        implementation fileTree('../lib') { include '*.jar' }

Template address:

Necessary jar packages:

spire.doc.free-5.2.0.jar

I will just paste the code here

Guide package:

import cn.hutool.core.collection.CollectionUtil;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.td.base.commons.ApiException;
import com.td.base.mappers.TStationPimMapper;
import com.td.base.models.TSerialized;
import com.td.base.models.TSerializedItems;
import com.td.base.models.TStationPim;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
public void downStatement(String serialNo, Integer isPdf, HttpServletResponse response) {
    Map<String, Object> map = new HashMap<String, Object>();
    TStationPim one =
        lambdaQuery()
            .eq(TStationPim::getSerialNo, serialNo)
            .orderByDesc(TStationPim::getOutTime)
            .last("limit 1")
            .one();
    if (Objects.nonNull(one)) {
      List<TSerialized> list =
          tSerializedService
              .lambdaQuery()
              .eq(TSerialized::getSerialNo, one.getSerialNo())
              .eq(TSerialized::getStationNo, one.getStationNo())
              .list();
      if (CollectionUtil.isNotEmpty(list)) {
        AtomicReference<String> result = new AtomicReference<>("Pass");
        list.forEach(
            x -> {
              if ("Fail".equals(x.getResult())) {
                result.set("Fail");
              }
            });
        List<TSerializedItems> data =
            tSerializedItemsService
                .lambdaQuery()
                .in(
                    TSerializedItems::getSerializedId,
                    list.stream().map(TSerialized::getId).collect(Collectors.toList()))
                .orderByDesc(TSerializedItems::getId)
                .list();
        map.put("lastTime", one.getOutTime());
        map.put("serialNo", one.getSerialNo());
        map.put("result", result.get());
        map.put("productId", list.get(0).getProductId());
        map.put("productDescription", list.get(0).getProductDescription());
        if (CollectionUtil.isNotEmpty(data)) {
          map.put("data", data);
        }
        try {
          exportFile2(map, "serial number template.ftl", "report", response);
        } catch (Exception e) {
          throw new ApiException("9001", "Parameter error!");
        }
      }
    } else {
      throw new ApiException("9001", "Parameter error!");
    }
  }

  /** Public method */
  public void exportFile(
      Map<String, Object> data, String name, String fileName, HttpServletResponse response)
      throws Exception {
    // Business code
    //Create configuration class
    Configuration configuration = new Configuration(Configuration.getVersion());
    configuration.setClassForTemplateLoading(this.getClass(), "/templates");
    // Get the template file
    Template template = configuration.getTemplate(name);
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
    InputStream inputStream = IOUtils.toInputStream(content);
    ServletOutputStream out = null;
    try {
      //output file
      response.setHeader("content-type", "application/octet-stream");
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename="
              .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8") + ".doc")));
      out = response.getOutputStream();
      byte[] buffer = new byte[1024]; // buffer
      int bytesToRead = -1;
      // Output the content of the read Word file to the browser through a loop
      while ((bytesToRead = inputStream.read(buffer)) != -1) {
        out.write(buffer, 0, bytesToRead);
      }
    } catch (Exception e) {
      log.error("Export exception{" + e.getMessage() + "}");
      throw new ApiException("9999");
    } finally {
      try {
        if (out != null) {
          out.flush();
        }
        if (out != null) {
          out.close();
        }
        inputStream.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

  /** Public method */
  public void exportFile2(
      Map<String, Object> data, String name, String fileName, HttpServletResponse response)
      throws TemplateException, IOException {
    // Business code
    //Create configuration class
    Configuration configuration = new Configuration(Configuration.getVersion());
    configuration.setClassForTemplateLoading(this.getClass(), "/templates");
    // Get the template file
    Template template = configuration.getTemplate(name);
    String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
    String filePath = "/data" + fileName + ".pdf";
    try (InputStream inputStream = IOUtils.toInputStream(content)) {
      Document document = new Document();
      document.loadFromStream(inputStream, FileFormat.Auto);
      document.saveToFile(filePath, FileFormat.PDF);
    }
    File file = new File(filePath);
    FileInputStream inputStream = new FileInputStream(file);
    // InputStream inputStream = IOUtils.toInputStream(content);
    ServletOutputStream out = null;
    try {
      //output file
      response.setHeader("content-type", "application/octet-stream");
      response.setContentType("application/octet-stream;charset=UTF-8");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename="
              .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8") + ".pdf")));
      out = response.getOutputStream();
      byte[] buffer = new byte[1024]; // buffer
      int bytesToRead = -1;
      // Output the content of the read Word file to the browser through a loop
      while ((bytesToRead = inputStream.read(buffer)) != -1) {
        out.write(buffer, 0, bytesToRead);
      }
    } catch (Exception e) {
      log.error("Export exception{" + e.getMessage() + "}");
      throw new ApiException("9999");
    } finally {
      try {
        if (out != null) {
          out.flush();
        }
        if (out != null) {
          out.close();
        }
        inputStream.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138,190 people are learning the system