freemark工具类
package com.odm.enterprise.utils;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import cn.hutool.core.lang.Assert;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@Component
public class FreeMarkerUtil {
private final Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
@PostConstruct
public void buildConfiguration() throws IOException {
this.cfg.setDefaultEncoding("UTF-8");
this.cfg.setTemplateLoader(new ClassTemplateLoader(new WordUtils().getClass().getClassLoader(),"/template"));
}
public static File createDoc(Map<?, ?> dataMap, Template template) {
String name = System.currentTimeMillis() + ".doc";
File f = new File(name);
try {
Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), StandardCharsets.UTF_8));
template.process(dataMap, w);
w.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return f;
}
public static void exportWord(InputStream templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(templatePath, "模板路径不能为空");
Assert.notNull(temDir, "临时文件路径不能为空");
Assert.notNull(fileName, "导出文件名不能为空");
Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
if (!temDir.endsWith("/")) {
temDir = temDir + File.separator;
}
File dir = new File(temDir);
if (!dir.exists()) {
dir.mkdirs();
}
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
MyXWPFDocument doc = new MyXWPFDocument(templatePath);
WordExportUtil.exportWord07(doc, params);
String tmpPath = temDir + fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
doc.write(fos);
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream out = response.getOutputStream();
doc.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
delFileWord(temDir, fileName);
}
}
public static void delFileWord(String filePath, String fileName) {
File file = new File(filePath + fileName);
File file1 = new File(filePath);
file.delete();
file1.delete();
}
public static String encodeImageToBase64(File file) throws Exception {
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new Exception("图片上传失败!");
}
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(data);
return base64;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String a = "张三";
a = new String(a.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
System.out.println(a);
}
public void export(HttpServletResponse response, Map<?, ?> map, String title, String templateName) {
File file;
Template freemarkerTemplate;
try {
freemarkerTemplate = cfg.getTemplate(templateName);
file = createDoc(map, freemarkerTemplate);
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, title);
FileUtils.writeBytes(file.getAbsolutePath(), response.getOutputStream());
FileUtils.deleteFile(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
private String renderTemplate(Template template, Object model) {
StringWriter result = new StringWriter();
try {
template.process(model, result);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
public void createFile(String ftlFileName, Object data, String filePath) {
Writer out = null;
try {
String result = this.renderTemplate(cfg.getTemplate(ftlFileName, "UTF-8"), data);
File file = new File(filePath);
if (file.exists()) {
FileUtils.deleteFile(filePath);
}
FileUtils.mkdirs(filePath);
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), StandardCharsets.UTF_8), 1024);
out.write(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getImageBase(String src) {
if (src == null || src == "") {
return "";
}
File file = new File(src);
if (!file.exists()) {
return "";
}
InputStream in = null;
byte[] data = null;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
public String getEmpAutograph(String filePath) {
String img = null;
if (StringUtils.isNotEmpty(filePath)) {
InputStream in = null;
byte[] picdata = null;
try {
in = new FileInputStream(filePath);
picdata = new byte[in.available()];
in.read(picdata);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
BASE64Encoder encoder = new BASE64Encoder();
img = encoder.encode(picdata);
return img;
} else {
return null;
}
}
public void outDocx(File documentFile, InputStream ins, String fileName,
HttpServletResponse response) throws IOException {
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
File docxFile = new File(fileName);
ZipOutputStream zipout = null;
InputStream in = null;
InputStream is = null;
try {
OutputStream os = new FileOutputStream(docxFile);
int bytesRead = 0;
byte[] buffer2 = new byte[8192];
while ((bytesRead = ins.read(buffer2, 0, 8192)) != -1) {
os.write(buffer2, 0, bytesRead);
}
os.close();
ins.close();
ZipFile zipFile = new ZipFile(docxFile);
Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
zipout = new ZipOutputStream(response.getOutputStream());
int len = -1;
byte[] buffer = new byte[1024];
while (zipEntrys.hasMoreElements()) {
ZipEntry next = zipEntrys.nextElement();
is = zipFile.getInputStream(next);
zipout.putNextEntry(new ZipEntry(next.toString()));
if ("word/document.xml".equals(next.toString())) {
in = new FileInputStream(documentFile);
while ((len = in.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
in.close();
} else {
while ((len = is.read(buffer)) != -1) {
zipout.write(buffer, 0, len);
}
is.close();
}
zipout.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (zipout != null) {
try {
zipout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (docxFile != null) {
try {
docxFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
documentFile.delete();
}
}
public File createDoc(Object dataMap,String ftlName,String wordName) {
Template t = null;
try {
t = cfg.getTemplate(ftlName);
} catch (IOException e) {
e.printStackTrace();
}
if(t==null){
return null;
}
File outFile = new File(wordName);
Writer out =null;
try {
out =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (Exception e1) {
e1.printStackTrace();
}
if(out==null){
return null;
}
try {
t.process(dataMap, out);
out.close();
} catch ( IOException | TemplateException e) {
e.printStackTrace();
}
return outFile;
}
public boolean exportDoc(String tempName, String docName, Map<?, ?> dataMap, HttpServletResponse resp) throws Exception {
boolean status = false;
ServletOutputStream sos = null;
InputStream fin = null;
if (resp != null) {
resp.reset();
}
Template t = null;
try {
t = cfg.getTemplate(tempName);
t.setEncoding("utf-8");
} catch (IOException e) {
e.printStackTrace();
}
String name = "temp" + (int) (Math.random() * 100000) + ".doc";
File outFile = new File(name);
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
status = true;
} catch (Exception e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fin = new FileInputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
resp.setCharacterEncoding("utf-8");
resp.setContentType("application/msword");
docName = new String(docName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
resp.setHeader("Content-disposition", "attachment;filename=" + docName + ".doc");
try {
sos = resp.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[512];
int bytesToRead = -1;
try {
while ((bytesToRead = fin.read(buffer)) != -1) {
sos.write(buffer, 0, bytesToRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fin != null)
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
if (sos != null)
try {
sos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (outFile != null)
outFile.delete();
}
return status;
}
}
Https文件地址转base64
package com.odm.enterprise.utils.image;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@Component
public class HttpRequestUtil {
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
byte[] data = null;
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes(StandardCharsets.UTF_8));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffers = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffers)) != -1) {
outStream.write(buffers, 0, len);
}
inputStream.close();
data = outStream.toByteArray();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (Exception ce) {
System.out.println(ce.getMessage());
}
BASE64Encoder encoder = new BASE64Encoder();
if (data == null) {
return " ";
}
return encoder.encode(data);
}
public static String getImageStrFromUrl(String imgURL) {
byte[] data = null;
HttpURLConnection conn = null;
try {
URL url = new URL(imgURL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.setReadTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
data = outStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
BASE64Encoder encoder = new BASE64Encoder();
if (data == null) {
return "";
}
return encoder.encode(data);
}
public static void main(String[] args) {
String get = httpsRequest("https://odm-b.oss-cn-shanghai.aliyuncs.com/odmfile/截屏2022-10-28 16.56.44eb0fb1f176474a7394bbf42ab7987738.png", "GET", null);
System.out.println(get);
}
}