将word文件转换成一张图

1 篇文章 0 订阅

将doc转为BufferedImage 修改图片大小后合成一张图片输出

package com.jaminye.zongsu.util;

import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author jamin
 * @date 2020/7/12 18:36
 */
@Component
public class ConvertUtil {

    static Logger logger = LoggerFactory.getLogger(ConvertUtil.class);

    /**
     * word转html
     *
     * @param inputStream
     */
    public static List<BufferedImage> doc2pdf(String convertFilePath, InputStream inputStream) {
        if (!getWordLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            //logger.debug("doc2pdf,解析水印失败,请重试");
            return null;
        }

        try {

            Document document = new Document(inputStream);
            for (int i = 0; i < document.getPageCount(); i++) {

            }
            ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.JPEG);
            imageSaveOptions.setJpegQuality(100);
            imageSaveOptions.setUseHighQualityRendering(true);
            imageSaveOptions.setPrettyFormat(true);
            imageSaveOptions.setUseAntiAliasing(true);
            imageSaveOptions.setUseHighQualityRendering(true);
            int pageCount = document.getPageCount();
            List<BufferedImage> imageList = new ArrayList<>();
            for (int i = 0; i < pageCount; i++) {
                OutputStream output = new ByteArrayOutputStream();
                imageSaveOptions.setPageIndex(i);

                document.save(output, imageSaveOptions);
                ImageInputStream imageInputStream = javax.imageio.ImageIO.createImageInputStream(parse(output));
                imageList.add(javax.imageio.ImageIO.read(imageInputStream));
            }
            inputStream.close();


            List<BufferedImage> bufferedImages = newList(imageList);

            return bufferedImages;
        } catch (Exception e) {
            logger.warn("doc转换出错");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * list转list
     * @param imageList
     * @return
     */
    public static List<BufferedImage> newList(List<BufferedImage> imageList) {
        int min = Integer.MAX_VALUE;
        for (BufferedImage bufferedImage : imageList) {
            int width = bufferedImage.getWidth();
            if (width < min) {
                min = width;
            }
        }
        List<BufferedImage> bufferedImages = new ArrayList<>();
        for (BufferedImage bufferedImage : imageList) {
            BufferedImage bufferedImage1 = null;
            try {
                bufferedImage1 = resizeImage(bufferedImage, min);
            } catch (IOException e) {
                e.printStackTrace();
            }
            bufferedImages.add(bufferedImage1);
        }
        return bufferedImages;
    }

    /**
     * 修改图片大小
     * @param prevImage
     * @param width
     * @return
     * @throws IOException
     */
    public static BufferedImage resizeImage(BufferedImage prevImage, int width) throws IOException {
        //io流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int height = prevImage.getHeight();
        BufferedImage image = new BufferedImage(width, prevImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.createGraphics();
        graphics.drawImage(prevImage, 0, 0, width, prevImage.getHeight(), null);
        ImageIO.write(image, "png", baos);
        baos.flush();
        baos.close();
        return image;
    }

    /**
     * out转in
     * @param out
     * @return
     * @throws Exception
     */
    public static ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }

    /**
     * 转换合并输出
     * @param convertFilePath
     * @param inputStream
     */
    public static void test(String convertFilePath, InputStream inputStream) {
        List<BufferedImage> bufferedImages = doc2pdf(convertFilePath, inputStream);
        BufferedImage bufferedImage = null;
        //io流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            bufferedImage = mergeImage(false, bufferedImages);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ImageIO.write(bufferedImage, "png", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(convertFilePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.write(baos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 合并图片
     *
     * @param isHorizontal
     * @param imgs
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(boolean isHorizontal, List<BufferedImage> imgs) throws IOException {
        // 生成新图片
        BufferedImage destImage = null;
        // 计算新图片的长和高
        int allw = 0, allh = 0, allwMax = 0, allhMax = 0;
        // 获取总长、总宽、最长、最宽
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            allw += img.getWidth();

            if (imgs.size() != i + 1) {
                allh += img.getHeight() + 5;
            } else {
                allh += img.getHeight();
            }


            if (img.getWidth() > allwMax) {
                allwMax = img.getWidth();
            }
            if (img.getHeight() > allhMax) {
                allhMax = img.getHeight();
            }
        }
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allwMax, allh, BufferedImage.TYPE_INT_RGB);
        }
        Graphics2D g2 = (Graphics2D) destImage.getGraphics();
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, allw, allh);
        g2.setPaint(Color.RED);

        // 合并所有子图片到新图片
        int wx = 0, wy = 0;
        for (int i = 0; i < imgs.size(); i++) {
            BufferedImage img = imgs.get(i);
            int w1 = img.getWidth();
            int h1 = img.getHeight();
            // 从图片中读取RGB
            int[] ImageArrayOne = new int[w1 * h1];
            // 逐行扫描图像中各个像素的RGB到数组中
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1);
            // 水平方向合并
            if (isHorizontal) {
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1);

            } else {
                // 垂直方向合并
                // 设置上半部分或左半部分的RGB
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1);
            }
            wx += w1;
            wy += h1 + 5;
        }


        return destImage;
    }


    private static boolean getWordLicense() {
        boolean result = false;
        try {
            // 凭证
            String licenseStr =
                    "<License>\n"
                            + " <Data>\n"
                            + " <Products>\n"
                            + " <Product>Aspose.Total for Java</Product>\n"
                            + " <Product>Aspose.Words for Java</Product>\n"
                            + " </Products>\n"
                            + " <EditionType>Enterprise</EditionType>\n"
                            + " <SubscriptionExpiry>20991231</SubscriptionExpiry>\n"
                            + " <LicenseExpiry>20991231</LicenseExpiry>\n"
                            + " <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n"
                            + " </Data>\n"
                            + " <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n"
                            + "</License>";
            InputStream license = new ByteArrayInputStream(
                    licenseStr.getBytes("UTF-8"));
            License asposeLic = new License();
            asposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jamin_Ye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值