Commit d5f7ebc4 by songxiang

错题本2.75期相关代码

parent 56de0445
/*
* 武汉理工数字传播工程有限公司源代码,版权归武汉理工数字传播工程有限公司所有.
* 项目名称 : pcloud-common
* 创建日期 : 2017年3月3日
* 修改历史 :
* 1. [2017年3月3日]创建文件 by xnxqs
*/
package com.pcloud.common.constant;
/**
*
*
* @Author: songx
* @Date: 2019/7/29,14:11
*/
public class FilePathConstant {
/**
* 视频剪切文件夹
*/
public final static String CUT = getFolder("cut");
/**
* 下载文件夹
*/
public final static String DOWNLOAD = getFolder("download");
/**
* 生成图片地址
*/
public final static String IMAGE = getFolder("image");
/**
* 生成带水印文件夹
*/
public final static String IMAGE_WATERMARK = getFolder("image/watermark");
/**
* 生成音频文件夹
*/
public final static String AUDIO = getFolder("audio");
/**
* 生成PDF文件夹
*/
public final static String PDF = getFolder("pdf");
/**
* 生成WORD文件夹
*/
public final static String WORD = getFolder("word");
/**
* 生成TEXT文件夹
*/
public final static String TEXT = getFolder("text");
/**
* 组装文件夹路径
*
* @param folderName
* @return
*/
private static String getFolder(String folderName) {
return OSConstant.USERDIR + OSConstant.SEPARATOR + "files" + folderName + OSConstant.SEPARATOR;
}
}
package com.pcloud.common.dto;
import com.pcloud.common.dto.BaseDto;
import java.math.BigDecimal;
/**
* @Describe: TODO
* @Author: zhangdongwei
* @Date: Create on 11:35 2019/7/24 0024
*/
public class StoreFlowInfoDto extends BaseDto {
/**
* 标识(appId/productId/bookGroupId)
*/
private Long originId;
/**
* 类型(APP/PRODUCT/BOOK_GROUP)
*/
private String originType;
/**
*具体类型
*/
private String typeCode;
/**
* 标题
*/
private String title;
/**
* 封面图片
*/
private String coverImg;
/**
* 价格
*/
private BigDecimal price;
/**
* 开始时间(MM-dd)
*/
private String startDate;
/**
* 结束时间(MM-dd)
*/
private String endDate;
/**
* 数量(应用、作品下的资源数量, 社群书的群数量,等)
*/
private Integer resourceNum;
/**
* 数量(资源的item数量,群的成员数量,等)
*/
private Integer resourceItemNum;
public Long getOriginId() {
return originId;
}
public void setOriginId(Long originId) {
this.originId = originId;
}
public String getOriginType() {
return originType;
}
public void setOriginType(String originType) {
this.originType = originType;
}
public String getTypeCode() {
return typeCode;
}
public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCoverImg() {
return coverImg;
}
public void setCoverImg(String coverImg) {
this.coverImg = coverImg;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getResourceNum() {
return resourceNum;
}
public void setResourceNum(Integer resourceNum) {
this.resourceNum = resourceNum;
}
public Integer getResourceItemNum() {
return resourceItemNum;
}
public void setResourceItemNum(Integer resourceItemNum) {
this.resourceItemNum = resourceItemNum;
}
@Override
public String toString() {
return "StoreFlowInfoDto{" +
"originId=" + originId +
", originType='" + originType + '\'' +
", typeCode='" + typeCode + '\'' +
", title='" + title + '\'' +
", coverImg='" + coverImg + '\'' +
", price=" + price +
", startDate='" + startDate + '\'' +
", endDate='" + endDate + '\'' +
", resourceNum=" + resourceNum +
", resourceItemNum=" + resourceItemNum +
"} " + super.toString();
}
}
...@@ -29,7 +29,7 @@ import org.slf4j.Logger; ...@@ -29,7 +29,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConstant;
import com.pcloud.common.constant.OSConstant; import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
...@@ -215,7 +215,7 @@ public class FileUtils { ...@@ -215,7 +215,7 @@ public class FileUtils {
/** /**
* 传入文件夹路径,该方法能够实现创建整个路径 * 传入文件夹路径,该方法能够实现创建整个路径
* *
* @param path * @param filePath
* 文件夹路径,不包含文件名称及后缀名 * 文件夹路径,不包含文件名称及后缀名
*/ */
public static boolean isDir(String filePath) { public static boolean isDir(String filePath) {
...@@ -882,7 +882,7 @@ public class FileUtils { ...@@ -882,7 +882,7 @@ public class FileUtils {
String fileType = getFileType(url); String fileType = getFileType(url);
String localFilePath = url; String localFilePath = url;
if (url.startsWith("http")) { if (url.startsWith("http")) {
localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType; localFilePath = FilePathConstant.TEXT + UUIDUitl.taskName() + "." + fileType;
downloadFileFromUrl(url, localFilePath); downloadFileFromUrl(url, localFilePath);
} }
try { try {
...@@ -919,7 +919,7 @@ public class FileUtils { ...@@ -919,7 +919,7 @@ public class FileUtils {
return null; return null;
} }
// 下载文件 // 下载文件
String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType; String downloadPath = FilePathConstant.DOWNLOAD + UUIDUitl.generateString(32) + "." + fileType;
FileUtils.downloadFileFromUrl(url, downloadPath); FileUtils.downloadFileFromUrl(url, downloadPath);
// 剪切文件 // 剪切文件
String cutPath = clipByPercent(new File(downloadPath), percent); String cutPath = clipByPercent(new File(downloadPath), percent);
...@@ -969,7 +969,7 @@ public class FileUtils { ...@@ -969,7 +969,7 @@ public class FileUtils {
throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB"); throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB");
} }
// 输出文件路径 // 输出文件路径
String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName(); String outFilePath = FilePathConstant.CUT + UUIDUitl.generateString(12) + "_" + inputFile.getName();
creatFiles(outFilePath); creatFiles(outFilePath);
// 剪切长度 // 剪切长度
cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength; cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
......
...@@ -11,16 +11,12 @@ import java.math.BigDecimal; ...@@ -11,16 +11,12 @@ import java.math.BigDecimal;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.itextpdf.text.Image; import com.itextpdf.text.Image;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.ImageConstant; import com.pcloud.common.constant.ImageConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageEnum; import com.pcloud.common.enums.ImageEnum;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
...@@ -738,37 +734,32 @@ public class ImageUtils { ...@@ -738,37 +734,32 @@ public class ImageUtils {
* @param fileUrl * @param fileUrl
* @return * @return
*/ */
// public static UploadResultInfo transcodeToWebp(String fileUrl, int quality) { // public static UploadResultInfo transcodeToWebp(String fileUrl, int quality) {
// LOGGER.info("【IMAGE API】image transcode to webp.<START>.[fileUrl]=" + fileUrl // LOGGER.info("【IMAGE API】image transcode to webp.<START>.[fileUrl]=" + fileUrl + ",[quality]=" + quality);
// + ",[quality]=" + quality); // String fileNameAll = FileUtils.getFileNameAll(fileUrl);
// String fileNameAll = FileUtils.getFileNameAll(fileUrl); // String localFilePath = FilePathConstant.DOWNLOAD_PATH + fileNameAll;
// String localFilePath = FilePathConst.DOWNLOAD_PATH + fileNameAll; // FileUtils.downloadFileFromUrl(fileUrl, localFilePath);
// FileUtils.downloadFileFromUrl(fileUrl, localFilePath); // String outputFilePath = FilePathConstant.IMAGE_PATH + "webp/" + fileNameAll + ".webp";
// String outputFilePath = FilePathConst.IMAGE_PATH + "webp/" + fileNameAll + // FileUtils.creatFiles(outputFilePath);
// ".webp"; // UploadResultInfo uploadResultInfo = null;
// FileUtils.creatFiles(outputFilePath); // try {
// UploadResultInfo uploadResultInfo = null; // String os = System.getProperty("os.name");
// try { // if (os.toLowerCase().startsWith("win")) {
// String os = System.getProperty("os.name"); // executeCwebp4Win(localFilePath, outputFilePath, quality);
// if (os.toLowerCase().startsWith("win")) { // } else {
// executeCwebp4Win(localFilePath, outputFilePath, quality); // executeCwebp4Linux(localFilePath, outputFilePath, quality);
// } else { // }
// executeCwebp4Linux(localFilePath, outputFilePath, quality); // uploadResultInfo = OssUtils.uploadLocalFile4Child(outputFilePath, fileUrl);
// } // } catch (Exception e) {
// uploadResultInfo = OssUtils.uploadLocalFile4Child(outputFilePath, fileUrl); // LOGGER.error("An error happend when convert to webp. Img is: " + e.getMessage(), e);
// } catch (Exception e) { // throw new FileException(FileException.FILE_CONVERT_FAIL, "transcode to webp is fail!");
// LOGGER.error("An error happend when convert to webp. Img is: " + // } finally {
// e.getMessage(), e); // FileUtils.deleteFile(localFilePath);
// throw new FileException(FileException.FILE_CONVERT_FAIL, "transcode to webp // FileUtils.deleteFile(outputFilePath);
// is fail!"); // }
// } finally { // LOGGER.info("【IMAGE API】image transcode to webp.<START>.[uploadResultInfo]=" + uploadResultInfo);
// FileUtils.deleteFile(localFilePath); // return uploadResultInfo;
// FileUtils.deleteFile(outputFilePath); // }
// }
// LOGGER.info("【IMAGE API】image transcode to webp.<START>.[uploadResultInfo]="
// + uploadResultInfo);
// return uploadResultInfo;
// }
/** /**
* execute cwebp command:cwebp [options] input_file -o output_file.webp * execute cwebp command:cwebp [options] input_file -o output_file.webp
...@@ -778,15 +769,13 @@ public class ImageUtils { ...@@ -778,15 +769,13 @@ public class ImageUtils {
* @param quality * @param quality
* @throws Exception * @throws Exception
*/ */
// private static void executeCwebp4Win(String inputFilePath, String // private static void executeCwebp4Win(String inputFilePath, String outputFilePath, int quality) throws Exception {
// outputFilePath, int quality) throws Exception { // Process process = new ProcessBuilder("cwebp", "-q", (quality == 0 ? 80 : quality) + "", inputFilePath, "-o",
// Process process = new ProcessBuilder("cwebp", "-q", (quality == 0 ? 80 : // outputFilePath).redirectErrorStream(true).start();
// quality) + "", inputFilePath, "-o", // if (0 != process.waitFor()) {
// outputFilePath).redirectErrorStream(true).start(); // throw new Exception("process wait for fail!");
// if (0 != process.waitFor()) { // }
// throw new Exception("process wait for fail!"); // }
// }
// }
/** /**
* execute cwebp command:cwebp [options] input_file -o output_file.webp * execute cwebp command:cwebp [options] input_file -o output_file.webp
...@@ -796,47 +785,12 @@ public class ImageUtils { ...@@ -796,47 +785,12 @@ public class ImageUtils {
* @param quality * @param quality
* @throws Exception * @throws Exception
*/ */
// private static void executeCwebp4Linux(String inputFilePath, String // private static void executeCwebp4Linux(String inputFilePath, String outputFilePath, int quality) throws Exception {
// outputFilePath, int quality) throws Exception { // Process process = new ProcessBuilder("/usr/local/bin/cwebp", "-q", (quality == 0 ? 80 : quality) + "",
// Process process = new ProcessBuilder("/usr/local/bin/cwebp", "-q", (quality // inputFilePath, "-o", outputFilePath).redirectErrorStream(true).start();
// == 0 ? 80 : quality) + "", // if (0 != process.waitFor()) {
// inputFilePath, "-o", outputFilePath).redirectErrorStream(true).start(); // throw new Exception("process wait for fail!");
// if (0 != process.waitFor()) {
// throw new Exception("process wait for fail!");
// }
// }
/**
* 上传的图片转换成webpO
*
* @param localFilePath
* 源文件的本地路径
* @param httpUrl
* 源文件上传后的路径,主要用于子文件上传时对应http文件路径
*/
public static UploadResultInfo toWebp(String fileUrl) {
// String fileNameAll = FileUtils.getFileNameAll(fileUrl);
// String localFilePath = FilePathConst.DOWNLOAD_PATH + fileNameAll;
// FileUtils.downloadFileFromUrl(fileUrl, localFilePath);
// String tragetPath = null;
// try {
// tragetPath = com.dcg.util.ImageUtils.transcodeToWebp(localFilePath, 80);
// } catch (Exception e) {
// LOGGER.error("【IMAGE】图片转换成webp失败:" + e.getMessage(), e);
// return null;
// }
// if (StringUtils.isEmpty(tragetPath)) {
// return null;
// } // }
// try { // }
// return OssUtils.uploadLocalFile4Child(tragetPath, fileUrl);
// } catch (Exception e) {
// LOGGER.error("【IMAGE】图片转换成webp,上传失败:" + e.getMessage(), e);
// } finally {
// FileUtils.deleteFile(localFilePath);
// FileUtils.deleteFile(tragetPath);
// }
return null;
}
} }
package com.pcloud.common.utils;/** package com.pcloud.common.utils;/**
* Created by ${user} on ${date} * Created by ${user} on ${date}
*/ */
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageTypeEnum; import com.pcloud.common.enums.ImageTypeEnum;
import com.pcloud.common.utils.aliyun.OssUtils; import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.httpclient.SimpleHttpUtils; import com.pcloud.common.utils.httpclient.SimpleHttpUtils;
import com.pcloud.common.utils.json.JSONUtils; import com.pcloud.common.utils.json.JSONUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
/** /**
* @author TianChao * @author TianChao
* @date 2018/10/13 15:02 * @date 2018/10/13 15:02
*/ */
public class PictureUtil { public class PictureUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PictureUtil.class); private static final Logger LOGGER = LoggerFactory.getLogger(PictureUtil.class);
private static Color defaultColor = new Color(252, 252, 252); private static Color defaultColor = new Color(252, 252, 252);
private static Color borderColor = new Color(221, 221, 221); private static Color borderColor = new Color(221, 221, 221);
private static String playPic = "https://file.5rs.me/oss/uploadfe/png/3c687bffac4d885ecfff8517d6c3f9c2.png"; private static String playPic = "https://file.5rs.me/oss/uploadfe/png/3c687bffac4d885ecfff8517d6c3f9c2.png";
private static String defaultBackgroundPic = "https://oss.5rs.me/oss/uploadfe/png/3003b8978e85052f96ababdf7d46f70a.png"; private static String defaultBackgroundPic = "https://oss.5rs.me/oss/uploadfe/png/3003b8978e85052f96ababdf7d46f70a.png";
public static Color getImagePixel(BufferedImage bi) { public static Color getImagePixel(BufferedImage bi) {
if(bi.getWidth()*bi.getHeight()>500000) { if(bi.getWidth()*bi.getHeight()>500000) {
BufferedImage pic1 = new BufferedImage(157, 224, BufferedImage.SCALE_SMOOTH); BufferedImage pic1 = new BufferedImage(157, 224, BufferedImage.SCALE_SMOOTH);
Graphics graphics = pic1.getGraphics(); Graphics graphics = pic1.getGraphics();
graphics.drawImage(bi.getScaledInstance(157,224,Image.SCALE_SMOOTH),0,0,null); graphics.drawImage(bi.getScaledInstance(157,224,Image.SCALE_SMOOTH),0,0,null);
graphics.dispose(); graphics.dispose();
bi = pic1; bi = pic1;
} }
int width = bi.getWidth(); int width = bi.getWidth();
int height = bi.getHeight(); int height = bi.getHeight();
int sum=width*height; int sum=width*height;
int minx = bi.getMinX(); int minx = bi.getMinX();
int miny = bi.getMinY(); int miny = bi.getMinY();
int R = 0; int R = 0;
int G = 0; int G = 0;
int B = 0; int B = 0;
List<String> list=new ArrayList<>(); List<String> list=new ArrayList<>();
for (int i = minx; i < width; i++) { for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) { for (int j = miny; j < height; j++) {
int pixel = bi.getRGB(i, j); int pixel = bi.getRGB(i, j);
if(pixel==Color.white.getRGB() || pixel==Color.black.getRGB()){ if(pixel==Color.white.getRGB() || pixel==Color.black.getRGB()){
continue; continue;
} }
R =(pixel & 0xff0000) >> 16; R =(pixel & 0xff0000) >> 16;
G =(pixel & 0xff00) >> 8; G =(pixel & 0xff00) >> 8;
B =(pixel & 0xff); B =(pixel & 0xff);
if((R>230&&G>230&&B>230) ||(R<30&&G<30&&B<30)){ if((R>230&&G>230&&B>230) ||(R<30&&G<30&&B<30)){
continue; continue;
} }
list.add(R+"-"+G+"-"+B); list.add(R+"-"+G+"-"+B);
} }
} }
// R = R/sum; return getMaxCount(list);
// G = G/sum; }
// B = B/sum;
// return new Color(R,G,B);
return getMaxCount(list); public static Color getMaxCount(List<String> s) {
} List<String> list = s;
Map<String, Integer> map = new HashMap<String, Integer>();
for (String c : list) {
public static Color getMaxCount(List<String> s) { Integer l = map.get(c);
List<String> list = s; if (l == null)
Map<String, Integer> map = new HashMap<String, Integer>(); l = 1;
for (String c : list) { else
Integer l = map.get(c); l++;
if (l == null) map.put(c, l);
l = 1; }
else String max = null;
l++; long num = 0;
map.put(c, l); for (Map.Entry<String, Integer> entry : map.entrySet()) {
} String key = entry.getKey();
String max = null; Integer temp = entry.getValue();
long num = 0; if (max == null || temp > num) {
for (Map.Entry<String, Integer> entry : map.entrySet()) { max = key;
String key = entry.getKey(); num = temp;
Integer temp = entry.getValue(); }
if (max == null || temp > num) { }
max = key; String str[] = max.split("\\-");
num = temp; if (str.length == 3) {
} return new Color(Integer.parseInt(str[0]), Integer.parseInt(str[1]),
} Integer.parseInt(str[2]));
String str[] = max.split("\\-"); }
if (str.length == 3) { return Color.gray;
return new Color(Integer.parseInt(str[0]), Integer.parseInt(str[1]), }
Integer.parseInt(str[2]));
} public static String getB16(int R,int G,int B){
return Color.gray; String[] h=new String[256];
} h[0]="00";h[1]="01";h[2]="02";h[3]="03";h[4]="04";h[5]="05";
h[6]="06";h[7]="07";h[8]="08";h[9]="09";h[10]="0A";h[11]="0B";
public static String getB16(int R,int G,int B){ h[12]="0C";h[13]="0D";h[14]="0E";h[15]="0F";h[16]="10";h[17]="11";
String[] h=new String[256]; h[18]="12";h[19]="13";h[20]="14";h[21]="15";h[22]="16";h[23]="17";
h[0]="00";h[1]="01";h[2]="02";h[3]="03";h[4]="04";h[5]="05"; h[24]="18";h[25]="19";h[26]="1A";h[27]="1B";h[28]="1C";h[29]="1D";
h[6]="06";h[7]="07";h[8]="08";h[9]="09";h[10]="0A";h[11]="0B"; h[30]="1E";h[31]="1F";h[32]="20";h[33]="21";h[34]="22";h[35]="23";
h[12]="0C";h[13]="0D";h[14]="0E";h[15]="0F";h[16]="10";h[17]="11"; h[36]="24";h[37]="25";h[38]="26";h[39]="27";h[40]="28";h[41]="29";
h[18]="12";h[19]="13";h[20]="14";h[21]="15";h[22]="16";h[23]="17"; h[42]="2A";h[43]="2B";h[44]="2C";h[45]="2D";h[46]="2E";h[47]="2F";
h[24]="18";h[25]="19";h[26]="1A";h[27]="1B";h[28]="1C";h[29]="1D"; h[48]="30";h[49]="31";h[50]="32";h[51]="33";h[52]="34";h[53]="35";
h[30]="1E";h[31]="1F";h[32]="20";h[33]="21";h[34]="22";h[35]="23"; h[54]="36";h[55]="37";h[56]="38";h[57]="39";h[58]="3A";h[59]="3B";
h[36]="24";h[37]="25";h[38]="26";h[39]="27";h[40]="28";h[41]="29"; h[60]="3C";h[61]="3D";h[62]="3E";h[63]="3F";h[64]="40";h[65]="41";
h[42]="2A";h[43]="2B";h[44]="2C";h[45]="2D";h[46]="2E";h[47]="2F"; h[66]="42";h[67]="43";h[68]="44";h[69]="45";h[70]="46";h[71]="47";
h[48]="30";h[49]="31";h[50]="32";h[51]="33";h[52]="34";h[53]="35"; h[72]="48";h[73]="49";h[74]="4A";h[75]="4B";h[76]="4C";h[77]="4D";
h[54]="36";h[55]="37";h[56]="38";h[57]="39";h[58]="3A";h[59]="3B"; h[78]="4E";h[79]="4F";h[80]="50";h[81]="51";h[82]="52";h[83]="53";
h[60]="3C";h[61]="3D";h[62]="3E";h[63]="3F";h[64]="40";h[65]="41"; h[84]="54";h[85]="55";h[86]="56";h[87]="57";h[88]="58";h[89]="59";
h[66]="42";h[67]="43";h[68]="44";h[69]="45";h[70]="46";h[71]="47"; h[90]="5A";h[91]="5B";h[92]="5C";h[93]="5D";h[94]="5E";h[95]="6F";
h[72]="48";h[73]="49";h[74]="4A";h[75]="4B";h[76]="4C";h[77]="4D"; h[96]="60";h[97]="61";h[98]="62";h[99]="63";h[100]="64";h[101]="65";
h[78]="4E";h[79]="4F";h[80]="50";h[81]="51";h[82]="52";h[83]="53"; h[102]="66";h[103]="67";h[104]="68";h[105]="69";h[106]="6A";h[107]="6B";
h[84]="54";h[85]="55";h[86]="56";h[87]="57";h[88]="58";h[89]="59"; h[108]="6C";h[109]="6D";h[110]="6E";h[111]="6F";h[112]="70";h[113]="71";
h[90]="5A";h[91]="5B";h[92]="5C";h[93]="5D";h[94]="5E";h[95]="6F"; h[114]="72";h[115]="73";h[116]="74";h[117]="75";h[118]="76";h[119]="77";
h[96]="60";h[97]="61";h[98]="62";h[99]="63";h[100]="64";h[101]="65"; h[120]="78";h[121]="79";h[122]="7A";h[123]="7B";h[124]="7C";h[125]="7D";
h[102]="66";h[103]="67";h[104]="68";h[105]="69";h[106]="6A";h[107]="6B"; h[126]="7E";h[127]="7F";h[128]="80";h[129]="81";h[130]="82";h[131]="83";
h[108]="6C";h[109]="6D";h[110]="6E";h[111]="6F";h[112]="70";h[113]="71"; h[132]="84";h[133]="85";h[134]="86";h[135]="87";h[136]="88";h[137]="89";
h[114]="72";h[115]="73";h[116]="74";h[117]="75";h[118]="76";h[119]="77"; h[138]="8A";h[139]="8B";h[140]="8C";h[141]="8D";h[142]="8E";h[143]="8F";
h[120]="78";h[121]="79";h[122]="7A";h[123]="7B";h[124]="7C";h[125]="7D"; h[144]="90";h[145]="91";h[146]="92";h[147]="93";h[148]="94";h[149]="95";
h[126]="7E";h[127]="7F";h[128]="80";h[129]="81";h[130]="82";h[131]="83"; h[150]="96";h[151]="97";h[152]="98";h[153]="99";h[154]="9A";h[155]="9B";
h[132]="84";h[133]="85";h[134]="86";h[135]="87";h[136]="88";h[137]="89"; h[156]="9C";h[157]="9D";h[158]="9E";h[159]="9F";h[160]="A0";h[161]="A1";
h[138]="8A";h[139]="8B";h[140]="8C";h[141]="8D";h[142]="8E";h[143]="8F"; h[162]="A2";h[163]="A3";h[164]="A4";h[165]="A5";h[166]="A6";h[167]="A7";
h[144]="90";h[145]="91";h[146]="92";h[147]="93";h[148]="94";h[149]="95"; h[168]="A8";h[169]="A9";h[170]="AA";h[171]="AB";h[172]="AC";h[173]="AD";
h[150]="96";h[151]="97";h[152]="98";h[153]="99";h[154]="9A";h[155]="9B"; h[174]="AE";h[175]="AF";h[176]="B0";h[177]="B1";h[178]="B2";h[179]="B3";
h[156]="9C";h[157]="9D";h[158]="9E";h[159]="9F";h[160]="A0";h[161]="A1"; h[180]="B4";h[181]="B5";h[182]="B6";h[183]="B7";h[184]="B8";h[185]="B9";
h[162]="A2";h[163]="A3";h[164]="A4";h[165]="A5";h[166]="A6";h[167]="A7"; h[186]="BA";h[187]="BB";h[188]="BC";h[189]="BD";h[190]="BE";h[191]="BF";
h[168]="A8";h[169]="A9";h[170]="AA";h[171]="AB";h[172]="AC";h[173]="AD"; h[192]="C0";h[193]="C1";h[194]="C2";h[195]="C3";h[196]="C4";h[197]="C5";
h[174]="AE";h[175]="AF";h[176]="B0";h[177]="B1";h[178]="B2";h[179]="B3"; h[198]="C6";h[199]="C7";h[200]="C8";h[201]="C9";h[202]="CA";h[203]="CB";
h[180]="B4";h[181]="B5";h[182]="B6";h[183]="B7";h[184]="B8";h[185]="B9"; h[204]="CC";h[205]="CD";h[206]="CE";h[207]="CF";h[208]="D0";h[209]="D1";
h[186]="BA";h[187]="BB";h[188]="BC";h[189]="BD";h[190]="BE";h[191]="BF"; h[210]="D2";h[211]="D3";h[212]="D4";h[213]="D5";h[214]="D6";h[215]="D7";
h[192]="C0";h[193]="C1";h[194]="C2";h[195]="C3";h[196]="C4";h[197]="C5"; h[216]="D8";h[217]="D9";h[218]="DA";h[219]="DB";h[220]="DC";h[221]="DD";
h[198]="C6";h[199]="C7";h[200]="C8";h[201]="C9";h[202]="CA";h[203]="CB"; h[222]="DE";h[223]="DF";h[224]="E0";h[225]="E1";h[226]="E2";h[227]="E3";
h[204]="CC";h[205]="CD";h[206]="CE";h[207]="CF";h[208]="D0";h[209]="D1"; h[228]="E4";h[229]="E5";h[230]="E6";h[231]="E7";h[232]="E8";h[233]="E9";
h[210]="D2";h[211]="D3";h[212]="D4";h[213]="D5";h[214]="D6";h[215]="D7"; h[234]="EA";h[235]="EB";h[236]="EC";h[237]="ED";h[238]="EE";h[239]="EF";
h[216]="D8";h[217]="D9";h[218]="DA";h[219]="DB";h[220]="DC";h[221]="DD"; h[240]="F0";h[241]="F1";h[242]="F2";h[243]="F3";h[244]="F4";h[245]="F5";
h[222]="DE";h[223]="DF";h[224]="E0";h[225]="E1";h[226]="E2";h[227]="E3"; h[246]="F6";h[247]="F7";h[248]="F8";h[249]="F9";h[250]="FA";h[251]="FB";
h[228]="E4";h[229]="E5";h[230]="E6";h[231]="E7";h[232]="E8";h[233]="E9"; h[252]="FC";h[253]="FD";h[254]="FE";h[255]="FF";
h[234]="EA";h[235]="EB";h[236]="EC";h[237]="ED";h[238]="EE";h[239]="EF"; return "#"+h[R] + h[G] + h[B];
h[240]="F0";h[241]="F1";h[242]="F2";h[243]="F3";h[244]="F4";h[245]="F5"; }
h[246]="F6";h[247]="F7";h[248]="F8";h[249]="F9";h[250]="FA";h[251]="FB";
h[252]="FC";h[253]="FD";h[254]="FE";h[255]="FF"; public static Color getImagePixel(String imgFile) {
return "#"+h[R] + h[G] + h[B]; BufferedImage bi = null;
} Color imagePixel;
try {
public static Color getImagePixel(String imgFile) { if(imgFile.contains("http")){
BufferedImage bi = null; bi = ImageIO.read(new URL(imgFile));
Color imagePixel; }else{
try { bi = ImageIO.read(new File(imgFile));
if(imgFile.contains("http")){ }
bi = ImageIO.read(new URL(imgFile)); imagePixel = getImagePixel(bi);
}else{ } catch (Exception e) {
bi = ImageIO.read(new File(imgFile)); imagePixel = Color.gray;
} LOGGER.warn("生成图片失败,图片="+imgFile+","+e.getMessage(),e);
imagePixel = getImagePixel(bi); }
} catch (Exception e) { return imagePixel;
imagePixel = Color.gray; }
LOGGER.warn("生成图片失败,图片="+imgFile+","+e.getMessage(),e);
} public static String toBrowserHexValue(int number) {
return imagePixel; StringBuilder builder = new StringBuilder(
} Integer.toHexString(number & 0xff));
while (builder.length() < 2) {
public static String toBrowserHexValue(int number) { builder =new StringBuilder("0").append(builder);
StringBuilder builder = new StringBuilder( }
Integer.toHexString(number & 0xff)); return builder.toString().toUpperCase();
while (builder.length() < 2) { }
builder =new StringBuilder("0").append(builder);
} public static Color toColorFromString(String colorStr){
return builder.toString().toUpperCase(); colorStr = colorStr.substring(2);
} Color color = new Color(Integer.parseInt(colorStr, 16)) ;
return color;
public static Color toColorFromString(String colorStr){ }
colorStr = colorStr.substring(2);
Color color = new Color(Integer.parseInt(colorStr, 16)) ; private static BufferedImage subPicByWhite(BufferedImage picImage){
return color; return picImage.getSubimage(9, 9, 699, 300);
} }
private static BufferedImage subPicByWhite(BufferedImage picImage){
return picImage.getSubimage(9, 9, 699, 300);
} public static String getQrCover(String bookPic,boolean isDefault){
String resultPath = "";
try {
Color color = null;
public static String getQrCover(String bookPic,boolean isDefault){ try {
String resultPath = ""; color = getImagePixel(bookPic);
try { }catch (Exception e){
Color color = null; color = Color.gray;
try { }
color = getImagePixel(bookPic); String lightIcon = "https://oss.5rs.me/oss/uploadfe/png/12dcbc38528d926912c444765d786a9a.png";
}catch (Exception e){ String deepIcon = "https://oss.5rs.me/oss/uploadfe/png/60612a7415bdac8533568ae0c21a94b6.png";
color = Color.gray; String icon;
} if(color!=null && (color.getRed()<180||color.getBlue()<180||color.getGreen()<180)){
String lightIcon = "https://oss.5rs.me/oss/uploadfe/png/12dcbc38528d926912c444765d786a9a.png"; icon = lightIcon;
String deepIcon = "https://oss.5rs.me/oss/uploadfe/png/60612a7415bdac8533568ae0c21a94b6.png"; }else{
String icon; icon = deepIcon;
if(color!=null && (color.getRed()<180||color.getBlue()<180||color.getGreen()<180)){ }
icon = lightIcon; String html = "<div style = \"position: relative;width: 700px;height: 300px;border: 0px solid green;background-color: #fcfcfc;text-align: center;\"> <div style = \"position: absolute;width: 100%;height: 66%;background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");overflow: hidden;\"> <div style = \"position: absolute;top: 20px;right: -20px;background-image: url('"+icon+"');background-size: 100%;width: 219px;height: 149px;\"> </div> </div><div style=\"position: relative;display: inline-block;width: 158px;height: 225px;box-shadow: 0px 4px 14px 2px rgba(14, 47, 70, 0.2);border-radius: 4px;border: solid 1px #ddd; margin-top: 35px;background: url('"+bookPic+"') no-repeat;background-size: cover;background-position: center;\"></div></div>";
}else{ Map<String,String>header = new HashMap<>();
icon = deepIcon; header.put("Content-Type", "application/json");
} Map<String,String>param = new HashMap<>();
String html = "<div style = \"position: relative;width: 700px;height: 300px;border: 0px solid green;background-color: #fcfcfc;text-align: center;\"> <div style = \"position: absolute;width: 100%;height: 66%;background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");overflow: hidden;\"> <div style = \"position: absolute;top: 20px;right: -20px;background-image: url('"+icon+"');background-size: 100%;width: 219px;height: 149px;\"> </div> </div><div style=\"position: relative;display: inline-block;width: 158px;height: 225px;box-shadow: 0px 4px 14px 2px rgba(14, 47, 70, 0.2);border-radius: 4px;border: solid 1px #ddd; margin-top: 35px;background: url('"+bookPic+"') no-repeat;background-size: cover;background-position: center;\"></div></div>"; param.put("htmlCode",html);
Map<String,String>header = new HashMap<>(); String postResult = HttpKit.post("http://192.168.1.7:8216/transcode/htm2img/jpg", JSON.toJSONString(param));
header.put("Content-Type", "application/json"); Map map = JSONUtils.jsonToMap(postResult, String.class, String.class);
Map<String,String>param = new HashMap<>(); String pic = (String)map.get("data");
param.put("htmlCode",html); BufferedImage bookPicImage = ImageIO.read(new URL(pic));
String postResult = HttpKit.post("http://192.168.1.7:8216/transcode/htm2img/jpg", JSON.toJSONString(param)); BufferedImage bufferedImage = subPicByWhite(bookPicImage);
Map map = JSONUtils.jsonToMap(postResult, String.class, String.class); ByteArrayOutputStream os = new ByteArrayOutputStream();
String pic = (String)map.get("data"); ImageIO.write(bufferedImage, ImageTypeEnum.JPG.value, os);
BufferedImage bookPicImage = ImageIO.read(new URL(pic)); UploadResultInfo uploadResultInfo = OssUtils.uploadFileByte(os.toByteArray(), UUIDUitl.taskName(), ImageTypeEnum.JPG.value);
BufferedImage bufferedImage = subPicByWhite(bookPicImage); os.close();
ByteArrayOutputStream os = new ByteArrayOutputStream(); resultPath = uploadResultInfo == null ? null : uploadResultInfo.getUrl();
ImageIO.write(bufferedImage, ImageTypeEnum.JPG.value, os); } catch (Exception e) {
UploadResultInfo uploadResultInfo = OssUtils.uploadFileByte(os.toByteArray(), UUIDUitl.taskName(), ImageTypeEnum.JPG.value); LOGGER.error("生成合成图失败,url="+bookPic+"====="+e.getMessage(),e);
os.close(); }
resultPath = uploadResultInfo == null ? null : uploadResultInfo.getUrl(); return resultPath;
} catch (Exception e) {
LOGGER.error("生成合成图失败,url="+bookPic+"====="+e.getMessage(),e);
} }
return resultPath;
public static void main(String[] args) {
}
// String bookPic = "https://file.5rs.me/oss/upload/image/jpg/c2c7f0b85f9f4eb683cd86a2945bc5e5.jpg";
public static void main(String[] args) { String bookPic = "https://oss.5rs.me/oss/uploadfe/jpg/e88c2f608fe4365f5c0efd7dda0eb59e.jpg";
Color color;
if(bookPic.contains("/oss/")){
// String bookPic = "https://file.5rs.me/oss/upload/image/jpg/c2c7f0b85f9f4eb683cd86a2945bc5e5.jpg"; String s = SimpleHttpUtils.httpGet(bookPic + "?x-oss-process=image/average-hue", null);
String bookPic = "https://oss.5rs.me/oss/uploadfe/jpg/e88c2f608fe4365f5c0efd7dda0eb59e.jpg"; System.out.println(s);
Color color; Map map = JSONUtils.jsonToMap(s, String.class, String.class);
if(bookPic.contains("/oss/")){ String rgb = (String)map.get("RGB");
String s = SimpleHttpUtils.httpGet(bookPic + "?x-oss-process=image/average-hue", null); color = toColorFromString(rgb);
System.out.println(s); }else{
Map map = JSONUtils.jsonToMap(s, String.class, String.class); color = getImagePixel(bookPic);
String rgb = (String)map.get("RGB"); }
color = toColorFromString(rgb);
}else{ String lightIcon = "https://oss.5rs.me/oss/uploadfe/png/12dcbc38528d926912c444765d786a9a.png";
color = getImagePixel(bookPic); String deepIcon = "https://oss.5rs.me/oss/uploadfe/png/60612a7415bdac8533568ae0c21a94b6.png";
} String icon;
if(color!=null && (color.getRed()<180||color.getBlue()<180||color.getGreen()<180)){
String lightIcon = "https://oss.5rs.me/oss/uploadfe/png/12dcbc38528d926912c444765d786a9a.png"; icon = lightIcon;
String deepIcon = "https://oss.5rs.me/oss/uploadfe/png/60612a7415bdac8533568ae0c21a94b6.png"; }else{
String icon; icon = deepIcon;
if(color!=null && (color.getRed()<180||color.getBlue()<180||color.getGreen()<180)){ }
icon = lightIcon;
}else{ String html = "<div style = \"position: relative;width: 700px;height: 300px;border: 0px solid green;background-color: #fcfcfc;text-align: center;\"> <div style = \"position: absolute;width: 100%;height: 66%;background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");overflow: hidden;\"> <div style = \"position: absolute;top: 20px;right: -20px;background-image: url('"+icon+"');background-size: 100%;width: 219px;height: 149px;\"> </div> </div><div style=\"position: relative;display: inline-block;width: 158px;height: 225px;box-shadow: 0px 4px 14px 2px rgba(14, 47, 70, 0.2);border-radius: 4px;border: solid 1px #ddd; margin-top: 35px;background: url('"+bookPic+"') no-repeat;background-size: cover;background-position: center;\"></div></div>";
icon = deepIcon; Map<String,String>header = new HashMap<>();
} header.put("Content-Type", "application/json");
String html = "<div style = \"position: relative;width: 700px;height: 300px;border: 0px solid green;background-color: #fcfcfc;text-align: center;\"> <div style = \"position: absolute;width: 100%;height: 66%;background-color: rgb("+color.getRed()+","+color.getGreen()+","+color.getBlue()+");overflow: hidden;\"> <div style = \"position: absolute;top: 20px;right: -20px;background-image: url('"+icon+"');background-size: 100%;width: 219px;height: 149px;\"> </div> </div><div style=\"position: relative;display: inline-block;width: 158px;height: 225px;box-shadow: 0px 4px 14px 2px rgba(14, 47, 70, 0.2);border-radius: 4px;border: solid 1px #ddd; margin-top: 35px;background: url('"+bookPic+"') no-repeat;background-size: cover;background-position: center;\"></div></div>"; Map<String,String>param = new HashMap<>();
Map<String,String>header = new HashMap<>(); param.put("htmlCode",html);
header.put("Content-Type", "application/json");
String postResult = HttpKit.post("http://192.168.92.111:8214/transcode/htm2img/jpg", JSON.toJSONString(param));
Map<String,String>param = new HashMap<>();
param.put("htmlCode",html);
String postResult = HttpKit.post("http://192.168.92.111:8214/transcode/htm2img/jpg", JSON.toJSONString(param)); // String s = SimpleHttpUtils.httpRequest("http://localhost:8214/transcode/htm2img/jpg", param,"POST","utf-8",header);
Map map = JSONUtils.jsonToMap(postResult, String.class, String.class);
String pic = (String)map.get("data");
System.out.println(pic);
// String s = SimpleHttpUtils.httpRequest("http://localhost:8214/transcode/htm2img/jpg", param,"POST","utf-8",header);
Map map = JSONUtils.jsonToMap(postResult, String.class, String.class);
String pic = (String)map.get("data"); try {
System.out.println(pic); BufferedImage bookPicImage = ImageIO.read(new URL(pic));
BufferedImage bufferedImage = subPicByWhite(bookPicImage);
OutputStream os = new FileOutputStream("C:\\Users\\LiHao\\Desktop\\封面图\\result.jpg");
try { ImageIO.write(bufferedImage, ImageTypeEnum.JPG.value, os);
BufferedImage bookPicImage = ImageIO.read(new URL(pic)); os.close();
BufferedImage bufferedImage = subPicByWhite(bookPicImage); } catch (IOException e) {
OutputStream os = new FileOutputStream("C:\\Users\\LiHao\\Desktop\\封面图\\result.jpg"); e.printStackTrace();
ImageIO.write(bufferedImage, ImageTypeEnum.JPG.value, os); }
os.close();
} catch (IOException e) {
e.printStackTrace(); // String bookPic = "C:\\Users\\LiHao\\Desktop\\封面图\\aa.jpg";
} // String playPic = "C:\\Users\\LiHao\\Desktop\\封面图\\播放按钮.png";
// String defaultBackgroundPic = "C:\\Users\\LiHao\\Desktop\\封面图\\默认图背景.png";
// String resultPath = "C:\\Users\\LiHao\\Desktop\\封面图\\result.jpg";
// String bookPic = "C:\\Users\\LiHao\\Desktop\\封面图\\aa.jpg"; // Boolean isDefalut = false;
// String playPic = "C:\\Users\\LiHao\\Desktop\\封面图\\播放按钮.png"; // try {
// String defaultBackgroundPic = "C:\\Users\\LiHao\\Desktop\\封面图\\默认图背景.png"; // //取书封面和播放按钮图
// String resultPath = "C:\\Users\\LiHao\\Desktop\\封面图\\result.jpg"; // BufferedImage bookPicImage;
// Boolean isDefalut = false; // BufferedImage playPicImage;
// try { // BufferedImage defaultBackgroudImage;
// //取书封面和播放按钮图 // if(bookPic.contains("https:")){
// BufferedImage bookPicImage; // bookPicImage = ImageIO.read(new URL(bookPic));
// BufferedImage playPicImage; // playPicImage = ImageIO.read(new URL(playPic));
// BufferedImage defaultBackgroudImage; // defaultBackgroudImage = ImageIO.read(new URL(defaultBackgroundPic));
// if(bookPic.contains("https:")){ // }else{
// bookPicImage = ImageIO.read(new URL(bookPic)); // bookPicImage = ImageIO.read(new File(bookPic));
// playPicImage = ImageIO.read(new URL(playPic)); // playPicImage = ImageIO.read(new File(playPic));
// defaultBackgroudImage = ImageIO.read(new URL(defaultBackgroundPic)); // defaultBackgroudImage = ImageIO.read(new File(defaultBackgroundPic));
// }else{ // }
// bookPicImage = ImageIO.read(new File(bookPic)); //
// playPicImage = ImageIO.read(new File(playPic)); // //画一个空的背景
// defaultBackgroudImage = ImageIO.read(new File(defaultBackgroundPic)); // BufferedImage bg = new BufferedImage(702, 299, BufferedImage.TYPE_3BYTE_BGR);
// } // Graphics2D g = bg.createGraphics();
// // //获取主题色
// //画一个空的背景 // Color c = getImagePixel(bookPic);
// BufferedImage bg = new BufferedImage(702, 299, BufferedImage.TYPE_3BYTE_BGR); //
// Graphics2D g = bg.createGraphics(); //
// //获取主题色 // //画纯色的背景或者默认背景图
// Color c = getImagePixel(bookPic); // g.setColor(c);
// // if(isDefalut){
// // g.drawImage(defaultBackgroudImage.getScaledInstance(702,196, Image.SCALE_DEFAULT), 0, 0, null);
// //画纯色的背景或者默认背景图 // }else {
// g.setColor(c); // g.fillRect(0, 0, 702, 196);
// if(isDefalut){ // }
// g.drawImage(defaultBackgroudImage.getScaledInstance(702,196, Image.SCALE_DEFAULT), 0, 0, null); // g.setColor(new Color(252, 252, 252));
// }else { // g.fillRect(0, 196, 702, 102);
// g.fillRect(0, 0, 702, 196); //
// } // g.setColor(new Color(221, 221, 221));
// g.setColor(new Color(252, 252, 252)); // //插入书籍图和播放按钮
// g.fillRect(0, 196, 702, 102); // g.drawImage(bookPicImage.getScaledInstance(172,238, Image.SCALE_DEFAULT), 265, 30, null);
// // g.drawImage(playPicImage.getScaledInstance(80,80, Image.SCALE_DEFAULT), 306, 105, null);
// g.setColor(new Color(221, 221, 221)); // g.drawRect(265,30,172,238);
// //插入书籍图和播放按钮 //
// g.drawImage(bookPicImage.getScaledInstance(172,238, Image.SCALE_DEFAULT), 265, 30, null); // for(int i=0;i<3;i++){
// g.drawImage(playPicImage.getScaledInstance(80,80, Image.SCALE_DEFAULT), 306, 105, null); //
// g.drawRect(265,30,172,238); // }
// //
// for(int i=0;i<3;i++){ // //保存图片
// // if(bookPic.contains("https:")) {
// } // ByteArrayOutputStream os = new ByteArrayOutputStream();
// // ImageIO.write(bg, ImageTypeEnum.JPG.value, os);
// //保存图片 // UploadResultInfo uploadResultInfo = OssUtils.uploadFileByte(os.toByteArray(), UUIDUitl.taskName(), ImageTypeEnum.JPG.value);
// if(bookPic.contains("https:")) { // os.close();
// ByteArrayOutputStream os = new ByteArrayOutputStream(); // s = uploadResultInfo == null ? null : uploadResultInfo.getUrl();
// ImageIO.write(bg, ImageTypeEnum.JPG.value, os); // }else{
// UploadResultInfo uploadResultInfo = OssUtils.uploadFileByte(os.toByteArray(), UUIDUitl.taskName(), ImageTypeEnum.JPG.value); // OutputStream os = new FileOutputStream(resultPath);
// os.close(); // ImageIO.write(bg, ImageTypeEnum.JPG.value, os);
// s = uploadResultInfo == null ? null : uploadResultInfo.getUrl(); // os.close();
// }else{ // }
// OutputStream os = new FileOutputStream(resultPath); // System.out.println(s);
// ImageIO.write(bg, ImageTypeEnum.JPG.value, os); // } catch (Exception e) {
// os.close(); // System.out.println(e.getMessage());
// } // }
// System.out.println(s);
// } catch (Exception e) { }
// System.out.println(e.getMessage());
// }
}
}
}
...@@ -40,7 +40,7 @@ import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobRequest; ...@@ -40,7 +40,7 @@ import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobRequest;
import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobResponse.SnapshotJob; import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobResponse.SnapshotJob;
import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.DefaultProfile;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConstant;
import com.pcloud.common.constant.UrlConstant; import com.pcloud.common.constant.UrlConstant;
import com.pcloud.common.dto.OssImageCropDTO; import com.pcloud.common.dto.OssImageCropDTO;
import com.pcloud.common.dto.OssImageDTO; import com.pcloud.common.dto.OssImageDTO;
...@@ -1600,7 +1600,7 @@ public class OssUtils { ...@@ -1600,7 +1600,7 @@ public class OssUtils {
// 创建OSSClient实例 // 创建OSSClient实例
OSSClient ossClient = getOSSClient(bucketName); OSSClient ossClient = getOSSClient(bucketName);
// 生成新的图片地址 // 生成新的图片地址
String localPath = FilePathConst.IMAGE_PATH + UUIDUitl.generateString(32) + "." + fileType; String localPath = FilePathConstant.IMAGE + UUIDUitl.generateString(32) + "." + fileType;
FileUtils.creatFiles(localPath); FileUtils.creatFiles(localPath);
try { try {
ossClient.getObject(request, new File(localPath)); ossClient.getObject(request, new File(localPath));
...@@ -1720,7 +1720,7 @@ public class OssUtils { ...@@ -1720,7 +1720,7 @@ public class OssUtils {
// 创建OSSClient实例 // 创建OSSClient实例
OSSClient ossClient = getOSSClient(bucketName); OSSClient ossClient = getOSSClient(bucketName);
// 生成带水印的本地图片地址 // 生成带水印的本地图片地址
String localPath = FilePathConst.IMAGE_WATERMARK_PATH + fileName + "_" + LocalDateUtils.getYmdhmss() + "." String localPath = FilePathConstant.IMAGE_WATERMARK + fileName + "_" + LocalDateUtils.getYmdhmss() + "."
+ fileType; + fileType;
FileUtils.creatFiles(localPath); FileUtils.creatFiles(localPath);
ossClient.getObject(request, new File(localPath)); ossClient.getObject(request, new File(localPath));
......
...@@ -14,7 +14,6 @@ import org.apache.http.util.EntityUtils; ...@@ -14,7 +14,6 @@ import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.utils.rsa.MD5; import com.pcloud.common.utils.rsa.MD5;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
...@@ -25,17 +24,9 @@ import com.pcloud.common.utils.string.StringUtil; ...@@ -25,17 +24,9 @@ import com.pcloud.common.utils.string.StringUtil;
*/ */
public class UrlUtils { public class UrlUtils {
/**
*
*/
private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtils.class);
/** /**
* 请求地址(新郎接口)
*/
private static final String REQUEST_URL = "https://api.weibo.com/2/short_url/shorten.json?source=1681459862&url_long=";
/**
* 请求地址(OWN) * 请求地址(OWN)
*/ */
private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten"; private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten";
...@@ -51,20 +42,13 @@ public class UrlUtils { ...@@ -51,20 +42,13 @@ public class UrlUtils {
public static final String PRIVATE_KEY = "lgsc1205"; public static final String PRIVATE_KEY = "lgsc1205";
/** /**
* 获取短链接(新浪) * 获取短链接
* *
* @param long_url * @param long_url
* @return * @return
*/ */
public static String getShortUrl(String long_url) { public static String getShortUrl(String long_url) {
String result = callHttp(REQUEST_URL + long_url); return getShortUrl4Own(long_url);
if (StringUtil.isEmpty(result)) {
return null;
}
JSONObject resultObject = JSONObject.parseObject(result);
JSONArray array = resultObject.getJSONArray("urls");
JSONObject object = array.getJSONObject(0);
return object.getString("url_short");
} }
/** /**
......
...@@ -29,7 +29,7 @@ import com.itextpdf.text.pdf.PdfPTable; ...@@ -29,7 +29,7 @@ import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.text.pdf.PdfWriter;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConstant;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
...@@ -105,7 +105,7 @@ public class PdfUtils { ...@@ -105,7 +105,7 @@ public class PdfUtils {
*/ */
private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException { private static String pdfConvert(byte[] b, String fileName, String prefix, String format) throws FileException {
// 解析PDF文件 // 解析PDF文件
String outPath = FilePathConst.PDF_PATH + fileName + "_" + UUIDUitl.generateString(12); String outPath = FilePathConstant.PDF + fileName + "_" + UUIDUitl.generateString(12);
File fi = new File(outPath); File fi = new File(outPath);
if (!fi.exists()) { if (!fi.exists()) {
fi.mkdirs(); fi.mkdirs();
...@@ -161,7 +161,7 @@ public class PdfUtils { ...@@ -161,7 +161,7 @@ public class PdfUtils {
/** /**
* 创建PDF * 创建PDF
* *
* @param pdfChunkDOs * @param pdfPOs
* @return * @return
* @throws Exception * @throws Exception
*/ */
...@@ -176,7 +176,7 @@ public class PdfUtils { ...@@ -176,7 +176,7 @@ public class PdfUtils {
OutputStream os = null; OutputStream os = null;
try { try {
// 输出路径 // 输出路径
outPath = FilePathConst.PDF_PATH + UUIDUitl.taskName() + ".pdf"; outPath = FilePathConstant.PDF + UUIDUitl.taskName() + ".pdf";
FileUtils.creatFiles(outPath); FileUtils.creatFiles(outPath);
// 创建输出流 // 创建输出流
os = new FileOutputStream(new File(outPath)); os = new FileOutputStream(new File(outPath));
...@@ -358,10 +358,8 @@ public class PdfUtils { ...@@ -358,10 +358,8 @@ public class PdfUtils {
/** /**
* 加水印(字符串) * 加水印(字符串)
* *
* @param inputFile * @param filePath
* 需要加水印的PDF路径 * 需要加水印的PDF路径
* @param outputFile
* 输出生成PDF的路径
* @param waterMarkName * @param waterMarkName
* 水印字符 * 水印字符
*/ */
......
...@@ -590,5 +590,20 @@ public class StringUtil extends StringUtilParent { ...@@ -590,5 +590,20 @@ public class StringUtil extends StringUtilParent {
} }
return false; return false;
} }
/**
* 过滤HTML标签
*
* @param str
* @return
*/
public static String replaceHtml(String str) {
if (StringUtil.isEmpty(str)) {
return "";
}
Pattern p_html = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(str);
return m_html.replaceAll("").replaceAll("&nbsp;", "");
}
} }
package com.pcloud.common.utils.word; package com.pcloud.common.utils.word;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.math.BigInteger; import java.math.BigInteger;
import java.util.List; import java.util.List;
import org.apache.poi.POIXMLDocument; import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.util.Units; import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.HeaderFooterType; import org.apache.poi.wp.usermodel.HeaderFooterType;
import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFFooter; import org.apache.poi.xwpf.usermodel.XWPFFooter;
import org.apache.poi.xwpf.usermodel.XWPFHeader; import org.apache.poi.xwpf.usermodel.XWPFHeader;
import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture; import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFPictureData; import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConstant;
import com.pcloud.common.constant.WordConstant; import com.pcloud.common.constant.WordConstant;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.FileUtils; import com.pcloud.common.utils.FileUtils;
import com.pcloud.common.utils.ListUtils; import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.UUIDUitl; import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.common.utils.word.dto.ParagraphDTO; import com.pcloud.common.utils.word.dto.ParagraphDTO;
import com.pcloud.common.utils.word.dto.RunDTO; import com.pcloud.common.utils.word.dto.RunDTO;
import com.pcloud.common.utils.word.dto.RunImageDTO; import com.pcloud.common.utils.word.dto.RunImageDTO;
import com.pcloud.common.utils.word.dto.RunTableDTO; import com.pcloud.common.utils.word.dto.RunTableDTO;
import com.pcloud.common.utils.word.dto.RunTextDTO; import com.pcloud.common.utils.word.dto.RunTextDTO;
import com.pcloud.common.utils.word.dto.WordDTO; import com.pcloud.common.utils.word.dto.WordDTO;
import com.pcloud.common.utils.word.enums.ParagraphType; import com.pcloud.common.utils.word.enums.ParagraphType;
/** /**
* 重新定义word工具类 * 重新定义word工具类
* *
* @author:songx * @author:songx
* @date:2019/5/27,10:06 * @date:2019/5/27,10:06
*/ */
public class WordNewUtils { public class WordNewUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(WordNewUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(WordNewUtils.class);
// public static void main(String[] args) { // public static void main(String[] args) {
// List<ParagraphDTO> paragraphDTOS = new ArrayList<>(); // List<ParagraphDTO> paragraphDTOS = new ArrayList<>();
// // 页眉 // // 页眉
// paragraphDTOS.add(getHeader1()); // paragraphDTOS.add(getHeader1());
// paragraphDTOS.add(getHeader2()); // paragraphDTOS.add(getHeader2());
// // 标题 // // 标题
// paragraphDTOS.add(getParagraph1()); // paragraphDTOS.add(getParagraph1());
// // 内容 // // 内容
// paragraphDTOS.add(getParagraph2()); // paragraphDTOS.add(getParagraph2());
// paragraphDTOS.add(getParagraph3()); // paragraphDTOS.add(getParagraph3());
// paragraphDTOS.add(getParagraph4()); // paragraphDTOS.add(getParagraph4());
// paragraphDTOS.add(getParagraph4()); // paragraphDTOS.add(getParagraph4());
// // 页脚 // // 页脚
// paragraphDTOS.add(getFooter1()); // paragraphDTOS.add(getFooter1());
// try { // try {
// System.out.println(create(paragraphDTOS)); // System.out.println(create(paragraphDTOS));
// } catch (Exception e) { // } catch (Exception e) {
// LOGGER.error(e.getMessage(), e); // LOGGER.error(e.getMessage(), e);
// } // }
// System.out.println("Game over!"); // System.out.println("Game over!");
// } // }
// //
// private static ParagraphDTO getHeader1() { // private static ParagraphDTO getHeader1() {
// RunTextDTO runTextDTO = RunTextDTO // RunTextDTO runTextDTO = RunTextDTO
// .newText("?????的个人专属错题本 共40道错题", 9, "微软雅黑"); // .newText("?????的个人专属错题本 共40道错题", 9, "微软雅黑");
// return ParagraphDTO.newHeader(ParagraphType.text, runTextDTO); // return ParagraphDTO.newHeader(ParagraphType.text, runTextDTO);
// } // }
// //
// private static ParagraphDTO getHeader2() { // private static ParagraphDTO getHeader2() {
// RunTextDTO runTextDTO = RunTextDTO // RunTextDTO runTextDTO = RunTextDTO
// .newText("来源《书名书名书名书名书名书名书名书书名书名书名书书名书名书名书》", 9, "微软雅黑"); // .newText("来源《书名书名书名书名书名书名书名书书名书名书名书书名书名书名书》", 9, "微软雅黑");
// return ParagraphDTO.newHeader(ParagraphType.text, runTextDTO); // return ParagraphDTO.newHeader(ParagraphType.text, runTextDTO);
// } // }
// //
// private static ParagraphDTO getParagraph1() { // private static ParagraphDTO getParagraph1() {
// RunTextDTO runTextDTO = RunTextDTO // RunTextDTO runTextDTO = RunTextDTO
// .newText("个人专属错题本", 18, "微软雅黑", true); // .newText("个人专属错题本", 18, "微软雅黑", true);
// return ParagraphDTO.newParagraph(ParagraphType.text, ParagraphAlignment.CENTER, runTextDTO, 1); // return ParagraphDTO.newParagraph(ParagraphType.text, ParagraphAlignment.CENTER, runTextDTO, 1);
// } // }
// //
// private static ParagraphDTO getParagraph2() { // private static ParagraphDTO getParagraph2() {
// RunTextDTO runTextDTO = RunTextDTO // RunTextDTO runTextDTO = RunTextDTO
// .newText("完成下面错题练习,扫描二维码核对答案,并记录练习结果:", 11, "微软雅黑", true); // .newText("完成下面错题练习,扫描二维码核对答案,并记录练习结果:", 11, "微软雅黑", true);
// return ParagraphDTO.newParagraph(ParagraphType.text, runTextDTO, 1); // return ParagraphDTO.newParagraph(ParagraphType.text, runTextDTO, 1);
// } // }
// //
// private static ParagraphDTO getParagraph3() { // private static ParagraphDTO getParagraph3() {
// RunImageDTO runImageDTO = RunImageDTO // RunImageDTO runImageDTO = RunImageDTO
// .newImage("I:\\TEST\\image\\02.jpg", 80, 80, null, listAfterTexts3(11, "微软雅黑")); // .newImage("I:\\TEST\\image\\02.jpg", 80, 80, null, listAfterTexts3(11, "微软雅黑"));
// return ParagraphDTO.newParagraph(ParagraphType.image, TextAlignment.TOP, runImageDTO, 1); // return ParagraphDTO.newParagraph(ParagraphType.image, TextAlignment.TOP, runImageDTO, 1);
// } // }
// //
// private static ParagraphDTO getParagraph4() { // private static ParagraphDTO getParagraph4() {
// RunImageDTO runImageDTO = RunImageDTO // RunImageDTO runImageDTO = RunImageDTO
// .newImage("I:\\TEST\\image\\2.jpg", 200, 500); // .newImage("I:\\TEST\\image\\2.jpg", 200, 500);
// return ParagraphDTO.newParagraph(ParagraphType.image, runImageDTO, 3); // return ParagraphDTO.newParagraph(ParagraphType.image, runImageDTO, 3);
// } // }
// //
// private static ParagraphDTO getFooter1() { // private static ParagraphDTO getFooter1() {
// RunTextDTO runTextDTO = RunTextDTO.newText("反复练习,攻克错题", 11, "微软雅黑"); // RunTextDTO runTextDTO = RunTextDTO.newText("反复练习,攻克错题", 11, "微软雅黑");
// return ParagraphDTO.newFooter(ParagraphType.text, ParagraphAlignment.CENTER, runTextDTO); // return ParagraphDTO.newFooter(ParagraphType.text, ParagraphAlignment.CENTER, runTextDTO);
// } // }
// //
// /** // /**
// * 组装图片后面的文字 // * 组装图片后面的文字
// * // *
// * @param fontSize // * @param fontSize
// * @param fontFamily // * @param fontFamily
// * @return // * @return
// */ // */
// private static List<RunTextDTO> listAfterTexts3(int fontSize, String fontFamily) { // private static List<RunTextDTO> listAfterTexts3(int fontSize, String fontFamily) {
// List<RunTextDTO> afterRuns = Lists.newArrayList(); // List<RunTextDTO> afterRuns = Lists.newArrayList();
// afterRuns.add(RunTextDTO.newText(" 答对", fontSize, fontFamily)); // afterRuns.add(RunTextDTO.newText(" 答对", fontSize, fontFamily));
// afterRuns.add(RunTextDTO.newText(" 10 ", fontSize, fontFamily, UnderlinePatterns.SINGLE)); // afterRuns.add(RunTextDTO.newText(" 10 ", fontSize, fontFamily, UnderlinePatterns.SINGLE));
// afterRuns.add(RunTextDTO.newText("道题,答错", fontSize, fontFamily)); // afterRuns.add(RunTextDTO.newText("道题,答错", fontSize, fontFamily));
// afterRuns.add(RunTextDTO.newText(" 11 ", fontSize, fontFamily, UnderlinePatterns.SINGLE)); // afterRuns.add(RunTextDTO.newText(" 11 ", fontSize, fontFamily, UnderlinePatterns.SINGLE));
// afterRuns.add(RunTextDTO.newText("道题,日期", fontSize, fontFamily)); // afterRuns.add(RunTextDTO.newText("道题,日期", fontSize, fontFamily));
// afterRuns.add(RunTextDTO.newText(" " + LocalDateUtils.getDateNow() + " ", fontSize, fontFamily, // afterRuns.add(RunTextDTO.newText(" " + LocalDateUtils.getDateNow() + " ", fontSize, fontFamily,
// UnderlinePatterns.SINGLE)); // UnderlinePatterns.SINGLE));
// return afterRuns; // return afterRuns;
// } // }
/** /**
* 创建WORD * 创建WORD
* *
* @param wordDTO * @param wordDTO
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static String create(WordDTO wordDTO) throws FileException { public static String create(WordDTO wordDTO) throws FileException {
LOGGER.info("【WORD】创建WORD文档,<START>"); LOGGER.info("【WORD】创建WORD文档,<START>");
if (wordDTO == null || ListUtils.isEmpty(wordDTO.getParagraphs())) { if (wordDTO == null || ListUtils.isEmpty(wordDTO.getParagraphs())) {
return null; return null;
} }
String wordTemplate = null; String wordTemplate = null;
String outPath = null; String outPath = null;
CustomXWPFDocument document = null; CustomXWPFDocument document = null;
FileOutputStream fos = null; FileOutputStream fos = null;
try { try {
wordTemplate = FilePathConst.WORD_PATH + UUIDUitl.taskName() + ".docx"; wordTemplate = FilePathConstant.WORD + UUIDUitl.taskName() + ".docx";
FileUtils.downloadFileFromUrl(WordConstant.TEMPLATE_URL, wordTemplate); FileUtils.downloadFileFromUrl(WordConstant.TEMPLATE_URL, wordTemplate);
OPCPackage pack = POIXMLDocument.openPackage(wordTemplate); OPCPackage pack = POIXMLDocument.openPackage(wordTemplate);
document = new CustomXWPFDocument(pack); document = new CustomXWPFDocument(pack);
// 添加内容到文档中 // 添加内容到文档中
addParagraphs(wordDTO, document); addParagraphs(wordDTO, document);
// 生成目标word // 生成目标word
outPath = FilePathConst.WORD_PATH + UUIDUitl.taskName() + ".docx"; outPath = FilePathConstant.WORD + UUIDUitl.taskName() + ".docx";
fos = new FileOutputStream(outPath); fos = new FileOutputStream(outPath);
document.write(fos); document.write(fos);
fos.flush(); fos.flush();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【WORD】创建WORD文档失败:" + e.getMessage(), e); LOGGER.error("【WORD】创建WORD文档失败:" + e.getMessage(), e);
throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage()); throw new FileException(FileException.FILE_CONTENT_ERROR, e.getMessage());
} finally { } finally {
close(document, fos); close(document, fos);
FileUtils.deleteFile(wordTemplate); FileUtils.deleteFile(wordTemplate);
} }
LOGGER.info("【WORD】创建WORD文档,<END>.[outPath]=" + outPath); LOGGER.info("【WORD】创建WORD文档,<END>.[outPath]=" + outPath);
return outPath; return outPath;
} }
/** /**
* 添加内容到WORD中 * 添加内容到WORD中
* *
* @param wordDTO * @param wordDTO
* @param document * @param document
* @throws BizException * @throws BizException
*/ */
private static void addParagraphs(WordDTO wordDTO, CustomXWPFDocument document) { private static void addParagraphs(WordDTO wordDTO, CustomXWPFDocument document) {
List<ParagraphDTO> paragraphDTOS = wordDTO.getParagraphs(); List<ParagraphDTO> paragraphDTOS = wordDTO.getParagraphs();
for (ParagraphDTO paragraphDTO : paragraphDTOS) { for (ParagraphDTO paragraphDTO : paragraphDTOS) {
ParagraphType paragraphType = paragraphDTO.getParagraphType(); ParagraphType paragraphType = paragraphDTO.getParagraphType();
if (ParagraphType.table.equals(paragraphType)) { if (ParagraphType.table.equals(paragraphType)) {
addTable(paragraphDTO, document); addTable(paragraphDTO, document);
} else if (ParagraphType.image.equals(paragraphType)) { } else if (ParagraphType.image.equals(paragraphType)) {
addImage(wordDTO, paragraphDTO, document); addImage(wordDTO, paragraphDTO, document);
} else if (ParagraphType.text.equals(paragraphType)) { } else if (ParagraphType.text.equals(paragraphType)) {
addText(wordDTO, paragraphDTO, document); addText(wordDTO, paragraphDTO, document);
} }
} }
} }
/** /**
* 获取段落 * 获取段落
* *
* @param paragraphDTO * @param paragraphDTO
* @param document * @param document
* @return * @return
*/ */
private static XWPFParagraph getParagraph(ParagraphDTO paragraphDTO, CustomXWPFDocument document) { private static XWPFParagraph getParagraph(ParagraphDTO paragraphDTO, CustomXWPFDocument document) {
if (paragraphDTO.isHeader()) { if (paragraphDTO.isHeader()) {
XWPFHeader xwpfHeader = document.createHeader(HeaderFooterType.DEFAULT); XWPFHeader xwpfHeader = document.createHeader(HeaderFooterType.DEFAULT);
return xwpfHeader.createParagraph(); return xwpfHeader.createParagraph();
} else if (paragraphDTO.isFooter()) { } else if (paragraphDTO.isFooter()) {
XWPFFooter xwpfFooter = document.createFooter(HeaderFooterType.DEFAULT); XWPFFooter xwpfFooter = document.createFooter(HeaderFooterType.DEFAULT);
return xwpfFooter.createParagraph(); return xwpfFooter.createParagraph();
} else { } else {
return document.createParagraph(); return document.createParagraph();
} }
} }
/** /**
* 添加文本块 * 添加文本块
* *
* @param wordDTO * @param wordDTO
* @param paragraphDTO * @param paragraphDTO
* @throws BizException * @throws BizException
*/ */
private static void addText(WordDTO wordDTO, ParagraphDTO paragraphDTO, CustomXWPFDocument document) private static void addText(WordDTO wordDTO, ParagraphDTO paragraphDTO, CustomXWPFDocument document)
throws BizException { throws BizException {
XWPFParagraph paragraph = getParagraph(paragraphDTO, document); XWPFParagraph paragraph = getParagraph(paragraphDTO, document);
// 设置段落样式 // 设置段落样式
setParagraphStyle(paragraphDTO, paragraph); setParagraphStyle(paragraphDTO, paragraph);
// 设置段落块样式 // 设置段落块样式
if (paragraphDTO.getRun() != null) { if (paragraphDTO.getRun() != null) {
setTextStyle(wordDTO, (RunTextDTO) paragraphDTO.getRun(), paragraph); setTextStyle(wordDTO, (RunTextDTO) paragraphDTO.getRun(), paragraph);
} else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) { } else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) {
for (RunDTO runDTO : paragraphDTO.getRuns()) { for (RunDTO runDTO : paragraphDTO.getRuns()) {
setTextStyle(wordDTO, (RunTextDTO) runDTO, paragraph); setTextStyle(wordDTO, (RunTextDTO) runDTO, paragraph);
} }
} }
// 添加空行 // 添加空行
addEmptyText(paragraphDTO.getAfterEmpty(), document); addEmptyText(paragraphDTO.getAfterEmpty(), document);
} }
/** /**
* 添加空行 * 添加空行
* *
* @param afterEmpty * @param afterEmpty
* @param document * @param document
* @throws BizException * @throws BizException
*/ */
private static void addEmptyText(int afterEmpty, CustomXWPFDocument document) throws BizException { private static void addEmptyText(int afterEmpty, CustomXWPFDocument document) throws BizException {
for (int i = 0; i < afterEmpty; i++) { for (int i = 0; i < afterEmpty; i++) {
setTextStyle(null, RunTextDTO.newEmpty(), document.createParagraph()); setTextStyle(null, RunTextDTO.newEmpty(), document.createParagraph());
} }
} }
/** /**
* 设置段落样式 * 设置段落样式
* *
* @param paragraphDTO * @param paragraphDTO
* @param paragraph * @param paragraph
*/ */
private static void setParagraphStyle(ParagraphDTO paragraphDTO, XWPFParagraph paragraph) { private static void setParagraphStyle(ParagraphDTO paragraphDTO, XWPFParagraph paragraph) {
// 与前一行的间距 // 与前一行的间距
if (paragraphDTO.getSpacingBefore() > 0) { if (paragraphDTO.getSpacingBefore() > 0) {
paragraph.setSpacingBeforeLines(paragraphDTO.getSpacingBefore()); paragraph.setSpacingBeforeLines(paragraphDTO.getSpacingBefore());
} }
// 与下一行的间距 // 与下一行的间距
if (paragraphDTO.getSpacingAfter() > 0) { if (paragraphDTO.getSpacingAfter() > 0) {
paragraph.setSpacingAfterLines(paragraphDTO.getSpacingAfter()); paragraph.setSpacingAfterLines(paragraphDTO.getSpacingAfter());
} }
// 对齐 // 对齐
if (paragraphDTO.getParagraphAlignment() != null) { if (paragraphDTO.getParagraphAlignment() != null) {
paragraph.setFontAlignment(paragraphDTO.getParagraphAlignment().getValue()); paragraph.setFontAlignment(paragraphDTO.getParagraphAlignment().getValue());
} }
// 水平居中 // 水平居中
if (paragraphDTO.getTextAlignment() != null) { if (paragraphDTO.getTextAlignment() != null) {
paragraph.setVerticalAlignment(paragraphDTO.getTextAlignment()); paragraph.setVerticalAlignment(paragraphDTO.getTextAlignment());
} }
} }
/** /**
* 设置文本样式 * 设置文本样式
* *
* @param wordDTO * @param wordDTO
* @param runTextDTO * @param runTextDTO
* @param paragraph * @param paragraph
*/ */
private static void setTextStyle(WordDTO wordDTO, RunTextDTO runTextDTO, XWPFParagraph paragraph) { private static void setTextStyle(WordDTO wordDTO, RunTextDTO runTextDTO, XWPFParagraph paragraph) {
XWPFRun xwpfRun = paragraph.createRun(); XWPFRun xwpfRun = paragraph.createRun();
xwpfRun.setText(runTextDTO.getText()); xwpfRun.setText(runTextDTO.getText());
// 是否加粗 // 是否加粗
xwpfRun.setBold(runTextDTO.isBold()); xwpfRun.setBold(runTextDTO.isBold());
// 字体大小 // 字体大小
if (runTextDTO.getFontSize() > 0) { if (runTextDTO.getFontSize() > 0) {
xwpfRun.setFontSize(runTextDTO.getFontSize()); xwpfRun.setFontSize(runTextDTO.getFontSize());
} else if (wordDTO != null && wordDTO.getFontSize() > 0) { } else if (wordDTO != null && wordDTO.getFontSize() > 0) {
xwpfRun.setFontSize(wordDTO.getFontSize()); xwpfRun.setFontSize(wordDTO.getFontSize());
} }
// 字体 // 字体
if (runTextDTO.getFontFamily() != null) { if (runTextDTO.getFontFamily() != null) {
xwpfRun.setFontFamily(runTextDTO.getFontFamily()); xwpfRun.setFontFamily(runTextDTO.getFontFamily());
} else if (wordDTO != null && wordDTO.getFontFamily() != null) { } else if (wordDTO != null && wordDTO.getFontFamily() != null) {
xwpfRun.setFontFamily(wordDTO.getFontFamily()); xwpfRun.setFontFamily(wordDTO.getFontFamily());
} }
// 下划线 // 下划线
if (runTextDTO.getUnderlinePatterns() != null) { if (runTextDTO.getUnderlinePatterns() != null) {
xwpfRun.setUnderline(runTextDTO.getUnderlinePatterns()); xwpfRun.setUnderline(runTextDTO.getUnderlinePatterns());
} }
} }
/** /**
* 添加表格 * 添加表格
* *
* @param paragraphDTO * @param paragraphDTO
* @throws BizException * @throws BizException
*/ */
private static void addTable(ParagraphDTO paragraphDTO, CustomXWPFDocument document) throws BizException { private static void addTable(ParagraphDTO paragraphDTO, CustomXWPFDocument document) throws BizException {
XWPFParagraph paragraph = document.createParagraph(); XWPFParagraph paragraph = document.createParagraph();
// 设置段落样式 // 设置段落样式
setParagraphStyle(paragraphDTO, paragraph); setParagraphStyle(paragraphDTO, paragraph);
// 创建表格 // 创建表格
if (paragraphDTO.getRun() != null) { if (paragraphDTO.getRun() != null) {
createTable((RunTableDTO) paragraphDTO.getRun(), document); createTable((RunTableDTO) paragraphDTO.getRun(), document);
} else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) { } else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) {
for (RunDTO runDTO : paragraphDTO.getRuns()) { for (RunDTO runDTO : paragraphDTO.getRuns()) {
createTable((RunTableDTO) runDTO, document); createTable((RunTableDTO) runDTO, document);
} }
} }
// 添加空行 // 添加空行
addEmptyText(paragraphDTO.getAfterEmpty(), document); addEmptyText(paragraphDTO.getAfterEmpty(), document);
} }
/** /**
* 创建表格 * 创建表格
* *
* @param runTableDTO * @param runTableDTO
* @param document * @param document
*/ */
private static void createTable(RunTableDTO runTableDTO, CustomXWPFDocument document) { private static void createTable(RunTableDTO runTableDTO, CustomXWPFDocument document) {
String[][] contents = runTableDTO.getContents(); String[][] contents = runTableDTO.getContents();
if (contents == null || contents.length < 1) { if (contents == null || contents.length < 1) {
return; return;
} }
int rowNum = contents.length; // 总行数 int rowNum = contents.length; // 总行数
int colNum = runTableDTO.getColumnWidths().length; // 总列数 int colNum = runTableDTO.getColumnWidths().length; // 总列数
if (colNum < 1) { if (colNum < 1) {
throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致"); throw new FileException(FileException.FILE_CONTENT_ERROR, "表格列数与内容列数不一致");
} }
// 创建表格 // 创建表格
XWPFTable ComTable = document.createTable(); XWPFTable ComTable = document.createTable();
// 列宽自动分割 // 列宽自动分割
CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW(); CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
comTableWidth.setType(STTblWidth.DXA); comTableWidth.setType(STTblWidth.DXA);
comTableWidth.setW(BigInteger.valueOf(9072)); comTableWidth.setW(BigInteger.valueOf(9072));
// 设置行和列 // 设置行和列
for (int i = 0; i < rowNum; i++) { for (int i = 0; i < rowNum; i++) {
String[] cols = contents[i]; String[] cols = contents[i];
// 创建行 // 创建行
XWPFTableRow comTableRow = i == 0 ? ComTable.getRow(0) : ComTable.createRow(); XWPFTableRow comTableRow = i == 0 ? ComTable.getRow(0) : ComTable.createRow();
for (int j = 0; j < colNum; j++) { for (int j = 0; j < colNum; j++) {
String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j]; String text = (j >= cols.length || StringUtil.isEmpty(cols[j])) ? "" : cols[j];
// 填充单元格内容 // 填充单元格内容
XWPFTableCell cell = null; XWPFTableCell cell = null;
if (i == 0) { if (i == 0) {
cell = j == 0 ? comTableRow.getCell(0) : comTableRow.addNewTableCell(); cell = j == 0 ? comTableRow.getCell(0) : comTableRow.addNewTableCell();
} else { } else {
cell = comTableRow.getCell(j); cell = comTableRow.getCell(j);
} }
cell.setText(text); cell.setText(text);
cell.setVerticalAlignment(runTableDTO.getVertAlign()); cell.setVerticalAlignment(runTableDTO.getVertAlign());
} }
// 行高 // 行高
if (runTableDTO.getHeight() > 0) { if (runTableDTO.getHeight() > 0) {
comTableRow.setHeight(runTableDTO.getHeight()); comTableRow.setHeight(runTableDTO.getHeight());
} }
} }
} }
/** /**
* 添加图片和文本 * 添加图片和文本
* *
* @param paragraphDTO * @param paragraphDTO
* @param document * @param document
*/ */
private static void addImage(WordDTO wordDTO, ParagraphDTO paragraphDTO, CustomXWPFDocument document) { private static void addImage(WordDTO wordDTO, ParagraphDTO paragraphDTO, CustomXWPFDocument document) {
XWPFParagraph paragraph = null; XWPFParagraph paragraph = null;
if (paragraphDTO.isHeader()) { if (paragraphDTO.isHeader()) {
XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT); XWPFHeader header = document.createHeader(HeaderFooterType.DEFAULT);
paragraph = header.createParagraph(); paragraph = header.createParagraph();
addImageHeader(wordDTO, paragraphDTO, paragraph, header); addImageHeader(wordDTO, paragraphDTO, paragraph, header);
} else { } else {
paragraph = document.createParagraph(); paragraph = document.createParagraph();
addImageContent(wordDTO, paragraphDTO, paragraph, document); addImageContent(wordDTO, paragraphDTO, paragraph, document);
} }
// 设置段落样式 // 设置段落样式
setParagraphStyle(paragraphDTO, paragraph); setParagraphStyle(paragraphDTO, paragraph);
// 添加空行 // 添加空行
addEmptyText(paragraphDTO.getAfterEmpty(), document); addEmptyText(paragraphDTO.getAfterEmpty(), document);
} }
/** /**
* 页眉中插入图片 * 页眉中插入图片
* *
* @param wordDTO * @param wordDTO
* @param paragraphDTO * @param paragraphDTO
* @param paragraph * @param paragraph
* @param header * @param header
*/ */
private static void addImageHeader(WordDTO wordDTO, ParagraphDTO paragraphDTO, XWPFParagraph paragraph, private static void addImageHeader(WordDTO wordDTO, ParagraphDTO paragraphDTO, XWPFParagraph paragraph,
XWPFHeader header) { XWPFHeader header) {
// 创建图片 // 创建图片
if (paragraphDTO.getRun() != null) { if (paragraphDTO.getRun() != null) {
createImageHeader(wordDTO, (RunImageDTO) paragraphDTO.getRun(), paragraph, header); createImageHeader(wordDTO, (RunImageDTO) paragraphDTO.getRun(), paragraph, header);
} else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) { } else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) {
for (RunDTO runDTO : paragraphDTO.getRuns()) { for (RunDTO runDTO : paragraphDTO.getRuns()) {
createImageHeader(wordDTO, (RunImageDTO) runDTO, paragraph, header); createImageHeader(wordDTO, (RunImageDTO) runDTO, paragraph, header);
} }
} }
} }
/** /**
* 内容中插入图片 * 内容中插入图片
* *
* @param wordDTO * @param wordDTO
* @param paragraphDTO * @param paragraphDTO
* @param paragraph * @param paragraph
* @param document * @param document
*/ */
private static void addImageContent(WordDTO wordDTO, ParagraphDTO paragraphDTO, XWPFParagraph paragraph, private static void addImageContent(WordDTO wordDTO, ParagraphDTO paragraphDTO, XWPFParagraph paragraph,
CustomXWPFDocument document) { CustomXWPFDocument document) {
// 创建图片 // 创建图片
if (paragraphDTO.getRun() != null) { if (paragraphDTO.getRun() != null) {
createImageContent(wordDTO, (RunImageDTO) paragraphDTO.getRun(), paragraph, document); createImageContent(wordDTO, (RunImageDTO) paragraphDTO.getRun(), paragraph, document);
} else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) { } else if (!ListUtils.isEmpty(paragraphDTO.getRuns())) {
for (RunDTO runDTO : paragraphDTO.getRuns()) { for (RunDTO runDTO : paragraphDTO.getRuns()) {
createImageContent(wordDTO, (RunImageDTO) runDTO, paragraph, document); createImageContent(wordDTO, (RunImageDTO) runDTO, paragraph, document);
} }
} }
} }
/** /**
* 创建图片和文本 * 创建图片和文本
* *
* @param wordDTO * @param wordDTO
* @param runImageDTO * @param runImageDTO
* @param paragraph * @param paragraph
* @param document * @param document
*/ */
private static void createImageContent(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph, private static void createImageContent(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph,
CustomXWPFDocument document) { CustomXWPFDocument document) {
// 前置文本 // 前置文本
addImageBefore(wordDTO, runImageDTO, paragraph); addImageBefore(wordDTO, runImageDTO, paragraph);
try { try {
// 图片 // 图片
String relationId = addPictureContent(runImageDTO, document); String relationId = addPictureContent(runImageDTO, document);
if (!StringUtil.isEmpty(relationId)) { if (!StringUtil.isEmpty(relationId)) {
int id = document.getAllPictures().size() - 1; int id = document.getAllPictures().size() - 1;
document.createPicture(paragraph, relationId, id, runImageDTO.getWidth(), runImageDTO.getHeight()); document.createPicture(paragraph, relationId, id, runImageDTO.getWidth(), runImageDTO.getHeight());
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【WORD】创建WORD文档失败:" + e.getMessage(), e); LOGGER.error("【WORD】创建WORD文档失败:" + e.getMessage(), e);
} }
// 后置文本 // 后置文本
addImageAfter(wordDTO, runImageDTO, paragraph); addImageAfter(wordDTO, runImageDTO, paragraph);
} }
/** /**
* 创建图片 * 创建图片
* *
* @param wordDTO * @param wordDTO
* @param runImageDTO * @param runImageDTO
* @param paragraph * @param paragraph
* @param header * @param header
*/ */
private static void createImageHeader(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph, private static void createImageHeader(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph,
XWPFHeader header) { XWPFHeader header) {
// 前置文本 // 前置文本
addImageBefore(wordDTO, runImageDTO, paragraph); addImageBefore(wordDTO, runImageDTO, paragraph);
// 图片 // 图片
addPictureHeader(runImageDTO, paragraph, header); addPictureHeader(runImageDTO, paragraph, header);
// 后置文本 // 后置文本
addImageAfter(wordDTO, runImageDTO, paragraph); addImageAfter(wordDTO, runImageDTO, paragraph);
} }
/** /**
* 图片前置文本 * 图片前置文本
* *
* @param wordDTO * @param wordDTO
* @param runImageDTO * @param runImageDTO
* @param paragraph * @param paragraph
*/ */
private static void addImageBefore(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph) { private static void addImageBefore(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph) {
List<RunTextDTO> beforeTexts = runImageDTO.getBeforeTexts(); List<RunTextDTO> beforeTexts = runImageDTO.getBeforeTexts();
if (!ListUtils.isEmpty(beforeTexts)) { if (!ListUtils.isEmpty(beforeTexts)) {
for (RunTextDTO runTextDTO : beforeTexts) { for (RunTextDTO runTextDTO : beforeTexts) {
setTextStyle(wordDTO, runTextDTO, paragraph); setTextStyle(wordDTO, runTextDTO, paragraph);
} }
} }
} }
/** /**
* 图片后置文本 * 图片后置文本
* *
* @param wordDTO * @param wordDTO
* @param runImageDTO * @param runImageDTO
* @param paragraph * @param paragraph
*/ */
private static void addImageAfter(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph) { private static void addImageAfter(WordDTO wordDTO, RunImageDTO runImageDTO, XWPFParagraph paragraph) {
List<RunTextDTO> afterTexts = runImageDTO.getAfterTexts(); List<RunTextDTO> afterTexts = runImageDTO.getAfterTexts();
if (!ListUtils.isEmpty(afterTexts)) { if (!ListUtils.isEmpty(afterTexts)) {
for (RunTextDTO runTextDTO : afterTexts) { for (RunTextDTO runTextDTO : afterTexts) {
setTextStyle(wordDTO, runTextDTO, paragraph); setTextStyle(wordDTO, runTextDTO, paragraph);
} }
} }
} }
/** /**
* 添加页眉图片 * 添加页眉图片
* *
* @param runImageDTO * @param runImageDTO
* @param paragraph * @param paragraph
* @param header * @param header
*/ */
private static void addPictureHeader(RunImageDTO runImageDTO, XWPFParagraph paragraph, XWPFHeader header) { private static void addPictureHeader(RunImageDTO runImageDTO, XWPFParagraph paragraph, XWPFHeader header) {
InputStream is = null; InputStream is = null;
String imageUrl = runImageDTO.getImageUrl(); String imageUrl = runImageDTO.getImageUrl();
if (!StringUtil.isEmpty(imageUrl)) { if (!StringUtil.isEmpty(imageUrl)) {
if (imageUrl.startsWith("http")) { if (imageUrl.startsWith("http")) {
is = new ByteArrayInputStream(FileUtils.downloadByteFromUrl(imageUrl)); is = new ByteArrayInputStream(FileUtils.downloadByteFromUrl(imageUrl));
} else { } else {
is = new ByteArrayInputStream(FileUtils.file2byte(imageUrl)); is = new ByteArrayInputStream(FileUtils.file2byte(imageUrl));
} }
} else if (runImageDTO.getImageByte() != null) { } else if (runImageDTO.getImageByte() != null) {
is = new ByteArrayInputStream(runImageDTO.getImageByte()); is = new ByteArrayInputStream(runImageDTO.getImageByte());
} }
XWPFRun run = paragraph.createRun(); XWPFRun run = paragraph.createRun();
try { try {
XWPFPicture picture = run XWPFPicture picture = run
.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "123", Units.toEMU(runImageDTO.getWidth()), .addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "123", Units.toEMU(runImageDTO.getWidth()),
Units.toEMU(runImageDTO.getHeight())); Units.toEMU(runImageDTO.getHeight()));
//这段必须有,不然打开的logo图片不显示 //这段必须有,不然打开的logo图片不显示
String blipID = ""; String blipID = "";
for (XWPFPictureData picturedata : header.getAllPackagePictures()) { for (XWPFPictureData picturedata : header.getAllPackagePictures()) {
blipID = header.getRelationId(picturedata); blipID = header.getRelationId(picturedata);
} }
picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID); picture.getCTPicture().getBlipFill().getBlip().setEmbed(blipID);
run.addTab(); run.addTab();
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【WORD】WORD页眉图片生成失败:" + e.getMessage(), e); LOGGER.error("【WORD】WORD页眉图片生成失败:" + e.getMessage(), e);
} finally { } finally {
try { try {
if (is != null) { if (is != null) {
is.close(); is.close();
is = null; is = null;
} }
} catch (Exception e) { } catch (Exception e) {
} }
} }
} }
/** /**
* 添加图片数据 * 添加图片数据
* *
* @param runImageDTO * @param runImageDTO
* @param document * @param document
* @return * @return
* @throws InvalidFormatException * @throws InvalidFormatException
*/ */
private static String addPictureContent(RunImageDTO runImageDTO, CustomXWPFDocument document) private static String addPictureContent(RunImageDTO runImageDTO, CustomXWPFDocument document)
throws InvalidFormatException { throws InvalidFormatException {
String relationId = null; String relationId = null;
String imageUrl = runImageDTO.getImageUrl(); String imageUrl = runImageDTO.getImageUrl();
if (!StringUtil.isEmpty(imageUrl)) { if (!StringUtil.isEmpty(imageUrl)) {
if (imageUrl.startsWith("http")) { if (imageUrl.startsWith("http")) {
relationId = document.addPictureData(FileUtils.downloadByteFromUrl(imageUrl), relationId = document.addPictureData(FileUtils.downloadByteFromUrl(imageUrl),
XWPFDocument.PICTURE_TYPE_JPEG); XWPFDocument.PICTURE_TYPE_JPEG);
} else { } else {
relationId = document.addPictureData(FileUtils.file2byte(imageUrl), relationId = document.addPictureData(FileUtils.file2byte(imageUrl),
XWPFDocument.PICTURE_TYPE_JPEG); XWPFDocument.PICTURE_TYPE_JPEG);
} }
} else if (runImageDTO.getImageByte() != null) { } else if (runImageDTO.getImageByte() != null) {
relationId = document.addPictureData(runImageDTO.getImageByte(), XWPFDocument.PICTURE_TYPE_JPEG); relationId = document.addPictureData(runImageDTO.getImageByte(), XWPFDocument.PICTURE_TYPE_JPEG);
} }
return relationId; return relationId;
} }
/** /**
* 根据图片类型获取对应的图片类型代码 * 根据图片类型获取对应的图片类型代码
* *
* @param picType * @param picType
* @return * @return
*/ */
public static int getPictureType(String picType) { public static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT; int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) { if (picType != null) {
if (picType.equalsIgnoreCase("png")) { if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG; res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) { } else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB; res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) { } else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF; res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG; res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) { } else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF; res = CustomXWPFDocument.PICTURE_TYPE_WMF;
} }
} }
return res; return res;
} }
/** /**
* 结束关闭文件流 * 结束关闭文件流
* *
* @param document * @param document
* @param os * @param os
*/ */
public static void close(CustomXWPFDocument document, OutputStream os) { public static void close(CustomXWPFDocument document, OutputStream os) {
try { try {
if (document != null) { if (document != null) {
document.close(); document.close();
document = null; document = null;
} }
if (os != null) { if (os != null) {
os.close(); os.close();
os = null; os = null;
} }
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【WORD】WORD文件流关闭失败:" + e.getMessage(), e); LOGGER.error("【WORD】WORD文件流关闭失败:" + e.getMessage(), e);
} }
} }
} }
...@@ -41,7 +41,7 @@ import com.lowagie.text.Paragraph; ...@@ -41,7 +41,7 @@ import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase; import com.lowagie.text.Phrase;
import com.lowagie.text.Table; import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2; import com.lowagie.text.rtf.RtfWriter2;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConstant;
import com.pcloud.common.constant.WordConstant; import com.pcloud.common.constant.WordConstant;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
...@@ -84,7 +84,7 @@ public class WordUtils { ...@@ -84,7 +84,7 @@ public class WordUtils {
RtfWriter2 rtfWriter2 = null; RtfWriter2 rtfWriter2 = null;
try { try {
// 输出路径 // 输出路径
outPath = FilePathConst.WORD_PATH + UUIDUitl.taskName() + ".doc"; outPath = FilePathConstant.WORD + UUIDUitl.taskName() + ".doc";
FileUtils.creatFiles(outPath); FileUtils.creatFiles(outPath);
// 创建输出流 // 创建输出流
os = new FileOutputStream(new File(outPath)); os = new FileOutputStream(new File(outPath));
...@@ -302,14 +302,14 @@ public class WordUtils { ...@@ -302,14 +302,14 @@ public class WordUtils {
CustomXWPFDocument document = null; CustomXWPFDocument document = null;
FileOutputStream fos = null; FileOutputStream fos = null;
try { try {
wordTemplate = FilePathConst.WORD_PATH + UUIDUitl.taskName() + ".docx"; wordTemplate = FilePathConstant.WORD + UUIDUitl.taskName() + ".docx";
FileUtils.downloadFileFromUrl(WordConstant.TEMPLATE_URL, wordTemplate); FileUtils.downloadFileFromUrl(WordConstant.TEMPLATE_URL, wordTemplate);
OPCPackage pack = POIXMLDocument.openPackage(wordTemplate); OPCPackage pack = POIXMLDocument.openPackage(wordTemplate);
document = new CustomXWPFDocument(pack); document = new CustomXWPFDocument(pack);
// 添加内容到文档中 // 添加内容到文档中
addChunks(wordPOs, document); addChunks(wordPOs, document);
// 生成目标word // 生成目标word
outPath = FilePathConst.WORD_PATH + UUIDUitl.taskName() + ".docx"; outPath = FilePathConstant.WORD + UUIDUitl.taskName() + ".docx";
fos = new FileOutputStream(outPath); fos = new FileOutputStream(outPath);
document.write(fos); document.write(fos);
fos.flush(); fos.flush();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment