Java Word转为PNG

独自一人的江湖 / 2023-08-03 / 原文

  • 主要代码逻辑
//判断生成路径
File fileDir = new File("./generatePng");
if (!fileDir.exists()) {
fileDir.mkdirs();
}
String workPermitId = 唯一标识;
Document doc = new Document(word文档路径);
if (doc.getPageCount() > 1) {
//多张
for (int i = 0; i < doc.getPageCount(); i++) {
BufferedImage image = doc.saveToImages(i, ImageType.Bitmap);
File file = new File("./generatePng/" + workPermitId + (i + 1) + ".png");
ImageIO.write(image, "PNG", file);
}
//拼接图片
boolean isOk = mergeImage(workPermitId, doc.getPageCount(), 2, System.getProperty("user.dir") + "/generatePng/" + workPermitId + ".png");
if (!isOk) {
return AjaxResult.error("作业票图片生成失败,请重新尝试或确认是否存在word文档");
}
} else {
//单张
BufferedImage image = doc.saveToImages(0, ImageType.Bitmap);
File file = new File("./generatePng/" + workPermitId + ".png");
ImageIO.write(image, "PNG", file);
}
  • 拼接图片方法
/**
* 拼接图片(注:图片需长宽一致)
*
* @param len 图片数量
* @param type 1:横向拼接 2:纵向拼接
* @param targetFile 合成新的图片地址
*/
public static boolean mergeImage(String workPermitId,Integer len, int type, String targetFile) {
    // File[] src = new File[len];
BufferedImage[] images = new BufferedImage[len];
int[][] ImageArrays = new int[len][];

for (int i = 0; i < len; i++) {
try {
// src[i] = new File(files[i]);
images[i] = ImageIO.read(new File(System.getProperty("user.dir") + "/generatePng/" + workPermitId + (i + 1) + ".png"));
} catch (Exception e) {
log.error(e.getMessage(), e);
}

int width = images[i].getWidth();
int height = images[i].getHeight();
ImageArrays[i] = new int[width * height];
ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
}

int newHeight = 0;
int newWidth = 0;
for (int i = 0; i < images.length; i++) {
// 横向
if (type == 1) {
newHeight = newHeight > images[i].getHeight() ? newWidth : images[i].getHeight();
// 错误代码,原先没有添加+ 号
newWidth += images[i].getWidth();
} else if (type == 2) {
// 纵向
newWidth = newHeight > images[i].getWidth() ? newWidth : images[i].getWidth();
newHeight += images[i].getHeight();
}
}

if (type == 1 && newWidth < 1) {
return false;
}

if (type == 2 && newHeight < 1) {
return false;
}


try {
BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
int height_i = 0;
int width_i = 0;
for (int i = 0; i < images.length; i++) {
if (type == 1) {
ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0, images[i].getWidth());
width_i += images[i].getWidth();
} else if (type == 2) {
ImageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), ImageArrays[i], 0, newWidth);
height_i += images[i].getHeight();
}
}
// 输出想要的图片
ImageIO.write(ImageNew, targetFile.split("\\.")[1], new File(targetFile));
return true;
} catch (Exception e) {
log.error(e.getMessage(), e);
return false;
}
}