最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java通過Freemarker模板實現(xiàn)生成Word文件

 更新時間:2022年09月21日 15:12:42   作者:廢物大師兄  
FreeMarker是一款模板引擎: 即一種基于模板和要改變的數(shù)據(jù), 并用來生成輸出文本的通用工具。本文將根據(jù)Freemarker模板實現(xiàn)生成Word文件,需要的可以參考一下

1.  準(zhǔn)備模板

模板 + 數(shù)據(jù) = 模型

1、將準(zhǔn)備好的Word模板文件另存為.xml文件(PS:建議使用WPS來創(chuàng)建Word文件,不建議用Office)

2、將.xml文件重命名為.ftl文件

3、用文本編輯器打開.ftl文件,將內(nèi)容復(fù)制出來,格式化一下,再覆蓋原來的內(nèi)容

(PS:格式化一下是為了方便查找并設(shè)置變量/占位符,當(dāng)然設(shè)置好模板參數(shù)變量以后可以再壓縮后再寫會.ftl文件)

另外,強烈不建議在word文件中去編輯設(shè)置模板變量,因為.docx文件在另存為.xml文件后,原先好好的一個變量可能就被拆開了,建議另存為之后再用文本編輯器打開去編輯。

4、設(shè)置模板參數(shù)(變量/占位符)

2.  代碼實現(xiàn)

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo920</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo920</name>
    <description>demo920</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>5.8.7</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>
        <!--<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>22.9</version>
            <classifier>jdk17</classifier>
        </dependency>-->

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

寫個類測試一下

package com.example.demo920;

import com.example.demo920.domain.LoanReceipt;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@SpringBootTest
class Demo920ApplicationTests {

    private DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.CHINA);

    @Test
    void contextLoads() {
    }

    @Test
    void testGenerateWord() throws Exception {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");

        Template template = configuration.getTemplate("借條.ftl");

        Path path = Paths.get("tmp","contract");
        File fileDir = path.toFile();
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        String filename = "借條" + "_" + LocalDateTime.now().format(DTF) + ".docx";
        filename = path.toFile() + File.separator + filename;

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));

//        template.process(getDataMap(), writer);
        template.process(getData(), writer);

        writer.flush();
        writer.close();
    }

    Map<String, Object> getDataMap() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("borrowerName", "李白");
        dataMap.put("borrowerIdCard", "421302199001012426");
        dataMap.put("lenderName", "杜甫");
        dataMap.put("amount", 100);
        dataMap.put("amountInWords", "壹佰");
        dataMap.put("startDate", "2022年8月15日");
        dataMap.put("endDate", "2022年11月11日");
        dataMap.put("borrowingMonths", 3);
        dataMap.put("interestRate", "1.23");
        dataMap.put("guarantorName", "白居易");
        dataMap.put("guarantorIdCard", "421302199203152412");
        return dataMap;
    }

    LoanReceipt getData() {
        LoanReceipt receipt = new LoanReceipt();
        receipt.setBorrowerName("狄仁杰");
        receipt.setBorrowerIdCard("421302198710121234");
        receipt.setBorrowingMonths(6);
        receipt.setLenderName("李元芳");
        receipt.setAmount(new BigDecimal("101"));
        receipt.setAmountInWords("壹佰零壹");
        receipt.setInterestRate(new BigDecimal("0.6"));
        receipt.setStartDate("2022年1月1日");
        receipt.setEndDate("2022年6月30日");
        receipt.setGuarantorName("武則天");
        receipt.setGuarantorIdCard("421302199101014567");
        return receipt;
    }

}

最主要的是下面兩行

//	加載模板
Template template = configuration.getTemplate("借條.ftl");
//	填充數(shù)據(jù)
template.process(getData(), writer);

數(shù)據(jù)可以是Map也可以是一個對象

改進(jìn)一下,將生成文件的操作單獨寫成一個工具方法

package com.example.demo920.util;

import cn.hutool.core.io.IoUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;

public class FreemarkerUtils {

    /**
     * 生成Word
     * @param templateDir   模板所在的目錄
     * @param templateName  模板文件名稱
     * @param filename      生成的文件(含路徑)
     * @param dataModel     模板參數(shù)數(shù)據(jù)
     */
    public static void generateWord(File templateDir, String templateName, String filename, Object dataModel) {
        BufferedWriter writer = null;
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDefaultEncoding("UTF-8");
        try {
            configuration.setDirectoryForTemplateLoading(templateDir);
            Template template = configuration.getTemplate(templateName);
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
            template.process(dataModel, writer);
            writer.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(writer);
        }
    }

}

再測試一下

package com.example.demo920;

import cn.hutool.core.io.IoUtil;
import com.example.demo920.util.FreemarkerUtils;
import com.example.demo920.util.PdfUtils;
import org.junit.jupiter.api.Test;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

public class WordTest {

    /**
     * 1、從文件服務(wù)器下載模板文件
     * 2、根據(jù)業(yè)務(wù)類型獲取需要填充模板的數(shù)據(jù)
     * 3、模板+數(shù)據(jù)  再經(jīng)過處理生成新的文件
     * 4、將生成后的文件上傳到文件服務(wù)器,并返回一個文件ID
     * 5、業(yè)務(wù)可以保存這個文件ID或者文件的路徑
     */
    @Test
    void testGenerateWordV1() throws Exception {
        Path tempPath = Paths.get("tmp", "contract2");
        File path = tempPath.toFile();
        if (!path.exists()) {
            path.mkdirs();
        }
        File tempFile = Files.createTempFile(tempPath, "qiantiao", ".docx").toFile();
        System.out.println(tempFile.getParent());
        System.out.println(tempFile.getName());
        FileOutputStream fos = new FileOutputStream(tempFile);


        File templateFile = ResourceUtils.getFile("classpath:templates/借條.ftl");
        FileInputStream fis = new FileInputStream(templateFile);

        IoUtil.copy(fis, fos);

        String filename = "借條" + "_" + System.currentTimeMillis() + ".docx";
        filename = "tmp/contract" + File.separator + filename;

        FreemarkerUtils.generateWord(new File(tempFile.getParent()), tempFile.getName(), filename, getDataMap());
    }

 	/**
     * 獲取數(shù)據(jù)
     */
    Map<String, Object> getDataMap() {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("borrowerName", "李白2");
        dataMap.put("borrowerIdCard", "421302199001012426");
        dataMap.put("lenderName", "杜甫");
        dataMap.put("amount", 100);
        dataMap.put("amountInWords", "壹佰");
        dataMap.put("startDate", "2022年8月15日");
        dataMap.put("endDate", "2022年11月11日");
        dataMap.put("borrowingMonths", 3);
        dataMap.put("interestRate", "1.23");
        dataMap.put("guarantorName", "白居易");
        dataMap.put("guarantorIdCard", "421302199203152412");
        return dataMap;
    }

    @Test
    void testGenerateWord2() throws Exception {
        File templateDir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "templates");
        String templateName = "借條.ftl";
        String destFilename = "借條" + System.currentTimeMillis() + ".docx";
        Map<String, Object> data = getDataMap();
        FreemarkerUtils.generateWord(templateDir, templateName, destFilename, data);
    }

}

3. PDF文件加水印

有時候,生成或者從服務(wù)器下載的文件是需要加水印的,比如標(biāo)識這個文件是誰下載的之類的

pdf加水印還是比較方便的,用itext組件可以輕松實現(xiàn)

另外,如果最終需要pdf文件,建議直接生成pdf文件,跳過word轉(zhuǎn)pdf的步驟

package com.example.demo920.util;

import cn.hutool.core.io.IoUtil;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author chengjiansheng
 * @date 2022/09/21
 */
public class PdfUtils {

    /**
     * Word轉(zhuǎn)PDF
     * https://www.aspose.com/
     * 注意:Aspose.Words 這個組件是收費的,如果購買的話生成的PDF會有水印。
     * 可以去找相應(yīng)的破解版本,但是我感覺完全可以跳過Word直接生成PDF。
     * 比如,可以通過Freemarker直接生成PDF,或者利用iText通過模板生成PDF
     * @param src
     * @param dest
     */
    public static void wordToPdf(String src, String dest) {
        File file = new File(src);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            Document wpd = new Document(fis);
            wpd.save(dest, SaveFormat.PDF);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IoUtil.close(fis);
        }
    }

    /**
     * 加水印
     * @param src   源文件
     * @param dest  目標(biāo)文件
     * @param text  文字
     * @param imagePath 圖片地址
     */
    public static void addWatermark(String src, String dest, String text, String imagePath) {
        try {
            //  待加水印的文件
            PdfReader reader = new PdfReader(src);
            //  加完水印的文件
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
            //  字體
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            //  透明度
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.4f);
            //  PDF文件總頁數(shù)
            int total = reader.getNumberOfPages() + 1;
            //  循環(huán)對每一頁都加水印
            PdfContentByte content;
            for (int i = 1; i < total; i++) {
                //  水印在文本之上
                content = stamper.getOverContent(i);
                content.setGState(gs);

                if (null != imagePath) {
                    Image image = Image.getInstance(imagePath);
//                    image.setAbsolutePosition(150, 150);
//                    image.scaleToFit(300,300);
//                    content.addImage(image);

                    for (int x = 0; x < 700; x = x + 300) {
                        for (int y = 0; y < 900; y = y + 200) {
                            image.setAbsolutePosition(x+50, y+50);
                            image.scaleToFit(100,100);
                            content.addImage(image);
                        }
                    }
                }
                if (null != text) {
                    content.beginText();
                    content.setColorFill(BaseColor.RED);
                    content.setFontAndSize(baseFont, 20);
//                    content.showTextAligned(Element.ALIGN_CENTER, text, 50, 50, 45);

                    for (int x = 0; x < 700; x = x + 300) {
                        for (int y = 0; y < 900; y = y + 200) {
                            //水印內(nèi)容和水印位置
                            content.showTextAligned(Element.ALIGN_CENTER, "哈哈哈哈哈", x - 20, y + 10, 30);
                            content.showTextAligned(Element.ALIGN_CENTER, LocalDateTime.now().toString(), x, y, 30);
                        }
                    }

                    content.endText();
                }
            }
            stamper.close();
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
    }
}

跑一下

@Test
void testWatermark() {
    String src2 = "D:\\借條_2.pdf";
    String dest2 = "D:\\借條_3.pdf";
    String imagePath = "D:\\1.jpg";
    PdfUtils.addWatermark(src2, dest2, "哈哈哈哈哈", imagePath);
}

加完水印后效果如圖

最后,示例項目結(jié)構(gòu)如圖

以上就是Java通過Freemarker模板實現(xiàn)生成Word文件的詳細(xì)內(nèi)容,更多關(guān)于Java Freemarker生成Word的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java中Runnable和Thread的區(qū)別分析

    Java中Runnable和Thread的區(qū)別分析

    在java中可有兩種方式實現(xiàn)多線程,一種是繼承Thread類,一種是實現(xiàn)Runnable接口,下面就拉分別介紹一下這兩種方法的優(yōu)缺點
    2013-03-03
  • struts+spring+hibernate三個框架的整合

    struts+spring+hibernate三個框架的整合

    這篇文章主要介紹了struts+spring+hibernate三個框架的整合,需要的朋友可以參考下
    2017-09-09
  • Java截取特定兩個標(biāo)記之間的字符串實例

    Java截取特定兩個標(biāo)記之間的字符串實例

    下面小編就為大家?guī)硪黄狫ava截取特定兩個標(biāo)記之間的字符串實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • Spring MVC 404 Not Found無錯誤日志的解決方法

    Spring MVC 404 Not Found無錯誤日志的解決方法

    這篇文章主要為大家詳細(xì)介紹了Spring MVC 404 Not Found無錯誤日志的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • springboot攔截器Interceptor的使用,你都了解嗎

    springboot攔截器Interceptor的使用,你都了解嗎

    springmvc 中的攔截器可以對請求進(jìn)行判別,在請求到達(dá)控制器之前,把非法的請求給攔截掉下面來說一說, 它在springboot中的使用,感興趣的朋友一起看看吧
    2021-07-07
  • 利用Springboot+Caffeine實現(xiàn)本地緩存實例代碼

    利用Springboot+Caffeine實現(xiàn)本地緩存實例代碼

    Caffeine是一個基于Java8開發(fā)的提供了近乎最佳命中率的高性能的緩存庫,下面這篇文章主要給大家介紹了關(guān)于利用Springboot+Caffeine實現(xiàn)本地緩存的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • mybatis中使用CASE?WHEN關(guān)鍵字報錯及解決

    mybatis中使用CASE?WHEN關(guān)鍵字報錯及解決

    這篇文章主要介紹了mybatis中使用CASE?WHEN關(guān)鍵字報錯及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Java kafka如何實現(xiàn)自定義分區(qū)類和攔截器

    Java kafka如何實現(xiàn)自定義分區(qū)類和攔截器

    這篇文章主要介紹了Java kafka如何實現(xiàn)自定義分區(qū)類和攔截器,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • Java?I/O流使用示例詳解

    Java?I/O流使用示例詳解

    Java.io?包幾乎包含了所有操作輸入、輸出需要的類。所有這些流類代表了輸入源和輸出目標(biāo)。本文將通過示例為大家詳細(xì)講講?I/O流的使用教程,需要的可以參考一下
    2022-08-08
  • Spring Cloud 2020.0.0正式發(fā)布再見了Netflix

    Spring Cloud 2020.0.0正式發(fā)布再見了Netflix

    這篇文章主要介紹了Spring Cloud 2020.0.0正式發(fā)布再見了Netflix,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-12-12

最新評論

安化县| 辰溪县| 定边县| 金乡县| 深泽县| 佛山市| 南岸区| 香港 | 东乌珠穆沁旗| 陆河县| 罗平县| 罗平县| 莆田市| 新晃| 天水市| 云安县| 滁州市| 怀来县| 通城县| 大厂| 封丘县| 兰坪| 武夷山市| 监利县| 容城县| 明溪县| 定南县| 雷波县| 称多县| 外汇| 高清| 利津县| 清水河县| 明星| 福泉市| 三台县| 文成县| 冀州市| 右玉县| 富顺县| 虹口区|