当前位置:首页 >> 装修效果图
装修效果图

Java根据Freemarker堆栈生成Word文件

发布时间:2023-04-23 12:16 来源:装修效果图

utStreamWriter;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;@SpringBootTestclass 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 getDataMap() { Map 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");// 填充数据库template.process(getData(), writer);

数据库可以是Map也可以是一个某类

改进型一下,将作用于邮件的转换单独写成一个应用软件方法

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 堆栈模板数据库 */ 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、从邮件代理服务支架电子书堆栈邮件 * 2、根据业务类型获取需要填充堆栈的数据库 * 3、堆栈+数据库 再进一步经过处理作用于新的邮件 * 4、将作用于后的邮件上传到邮件代理服务支架,并留在一个邮件ID * 5、业务可以保存这个邮件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()); } /** * 获取数据库 */ Map getDataMap() { Map 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 data = getDataMap(); FreemarkerUtils.generateWord(templateDir, templateName, destFilename, data); }}

3. PDF邮件滴印

有时候,作用于或者从代理服务支架电子书的邮件是需要滴印的,比如标识这个邮件是谁电子书的之类的

pdf滴印还是更为方便的,用itext子系统可以轻松付诸

另外,如果最后需要pdf邮件,表示同意这样一来作用于pdf邮件,跳过word转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转PDF * * 注意:Aspose.Words 这个子系统是HK$的,如果购买的话作用于的PDF都会有水印。 * 可以去找也就是说的解开版本,但是我感觉完全可以跳过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 最后目标邮件 * @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邮件总页数 int total = reader.getNumberOfPages() + 1; // 循环对每一页都滴印 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) { //水印内容和水印位置 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); } }}

赛跑一下

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

加完水印后效果如图

最后,示例项目结构如图

中文翻译链接:_source=tuicoolWildutm_medium=referral

人体增强免疫力吃什么
感冒喉咙痛吃点什么药
科兴重组蛋白药物的特点
探望病人
肌肉酸疼怎样治疗好得快
相关阅读

北京2024年新地原材料--预期热门地块--朱辛庄0029地块

最新篇文章瞩目大众号“澎叔德兴德兴德兴”朱辛庄0029其余部分①、整体情况朝阳区最很多人瞩目的就是朱辛庄0029其余部分(这个其余部分我也更加瞩目,朱辛...

迪丽热巴机场图据悉!白色长款羔羊衣气质十足,口罩素颜难掩颜值

最近,迪丽托林寺出现在飞机场,而Price quot用餐图片Price quot由网路上外景的图片在网上引起争议,最近的穿着风格引起了大家的关注Price # 039;的讨论。并迅速上升到热搜榜...

Mysteel:“认房不用认贷”等政策将是近期一线救楼市极限采取措施

今看成该系列外交政策,一旦凌空,或将是现阶段预备队楼价救市的连续持续性采取措施。预备队大城市限制购买外交政策一旦全面持续性放开,必将造成预备队大城市生产力飙升,倡导涨幅攀升。因此,对于预备队大...

售楼处不少漂亮女生,一年也卖不出几套房,咋就平庸得津津有味?

弥斯回去,导致住所收不出去,所以售楼部简单年长男孩子,年长男孩子也比班上出货业绩都会低很多。据了解到在售楼部,通常一个月初的销冠,90%以上都是男人,这点就离不开男孩子天然的占有优势了。...

离家出走十多天,独守空房的一爹俩娃,如今是什么景象?

是说的,阻挡才是不也就是说。 你认出的是,孩子们个性愈发越来越懒散、越来越甜蜜莫名其妙了,本来孩子们只是在拘押他人感受的压力。 3、过于过分孩子们的意识 之前...

友情链接