word转png图片 spring 版本

spring 版本 word转png图片


license.xml创建粘贴即可

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
      <Product>Aspose.Cells for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>
  </Data>
 <Signature>2sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

demo描述
本文包含word转png excel转png 由于excel转png顶部出现水印所以使用顶部裁剪的方式

package com.jeeplus.modules.api.util;



import com.aspose.cells.*;
import com.aspose.words.*;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.SaveFormat;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.utils.FileUtils;
import org.springframework.util.ResourceUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

/**
 * 封装文件 转 img
 */
public class WordUrlUtil {
    /**
     * licence 验证
     *
     * @return
     * @throws Exception
     */
    public static boolean getLicenseWord() throws Exception {
        boolean result = false;
        try {
            File file = ResourceUtils.getFile("classpath:license.xml");
            InputStream is = new FileInputStream(file);
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
            System.out.println("License 获取失败");
            e.printStackTrace();
            throw e;
        }
        return result;
    }
    /**
     * licence 验证
     *
     * @return
     * @throws Exception
     */
    public static boolean getLicenseExcel() throws Exception {
        boolean result = false;
        try {
            File file = ResourceUtils.getFile("classpath:license.xml");
            InputStream is = new FileInputStream(file);
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
            System.out.println("License 获取失败");
            e.printStackTrace();
            throw e;
        }
        return result;
    }
    /**
     * word文档转图片
     * [url=home.php?mod=space&uid=952169]@Param[/url] inPath 传入文档地址
     * @param inPath 文件地址
     * @param outDir 输出图片文件夹
     * @return 返回文件地址,以逗号分割
     */
    public static String doc2Img(String inPath, String outDir) {
        inPath = Global.getUserfilesBaseDir() + inPath;
        String address = outDir;
        outDir = Global.getUserfilesBaseDir() + outDir;

        FileUtils.createDirectory(outDir);
        String utls = "";
        try {
            if (!getLicenseWord()) {
                throw new Exception("com.aspose.words lic ERROR!");
            }
            System.out.println(inPath + " -> " + outDir);
            long old = System.currentTimeMillis();
            // word文档
            Document doc = new Document(inPath);

            // 支持RTF HTML,OpenDocument, PDF,EPUB, XPS转换
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            int pageCount = doc.getPageCount();

            for (int i = 0; i < pageCount; i++) {
                File file = new File(outDir + "/" + i + ".png");
                System.out.println(outDir + "/" + i + ".png");
                if (pageCount - 1 == i) {
                    utls += address + i + ".png";
                } else {
                    utls += address + i + ".png" + "|";
                }
                FileOutputStream os = new FileOutputStream(file);
                options.setPageIndex(i);
                doc.save(os, options);
                os.close();
            }
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return utls;
    }
/*
    *//**
     * excel 转 图片
     * @param inPath 文件地址
     * @param outDir 输出图片文件夹
     */
    public static String excelImg(String inPath, String outDir) {
        inPath = Global.getUserfilesBaseDir() + inPath;
        String address = outDir;
        outDir = Global.getUserfilesBaseDir() + outDir;

        FileUtils.createDirectory(outDir);
        String utls = "";
        try {
            if (!getLicenseExcel()) {
                throw new Exception("com.aspose.words lic ERROR!");
            }
            System.out.println(inPath + " -> " + outDir);
            long old = System.currentTimeMillis();
            //使用aspose读取excel
            Workbook book = new Workbook(inPath);
            //创建一个图表选项的对象
            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
            //设置图片类型
            imgOptions.setImageFormat(ImageFormat.getPng());
            imgOptions.setCellAutoFit(true);
            imgOptions.setOnePagePerSheet(true);
            //获取第一张工作表
            Worksheet sheet = book.getWorksheets().get(0);
            //创建一个纸张底色渲染对象
            SheetRender sr = new SheetRender(sheet, imgOptions);
            for (int j = 0; j < sr.getPageCount(); j++ )
            {
                //Generate an image for the worksheet
                sr.toImage(j, outDir +j+ ".png");
                utls+=address +j+ ".png";
                cutImage(outDir+j+ ".png",outDir+j+ ".png",0,16);//裁剪水印
            }
            long now = System.currentTimeMillis();
            System.out.println("convert OK! " + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return utls;


    }
    /**
     * 图片裁剪通用接口
     *
     * @param src  源图片地址,图片格式PNG
     * @param dest 目的图片地址
     * @param x    图片起始点x坐标
     * @param y    图片起始点y坐标
     * @throws IOException 异常处理
     */
    public static void cutImage(String src, String dest, int x, int y)  {
        try{
            //获取png图片的ImageReader的Iterator
            Iterator iterator = ImageIO.getImageReadersByFormatName("png");
            //根据Iterator获取ImageReader
            ImageReader reader = (ImageReader) iterator.next();
            //获取源图片输入流
            InputStream in = new FileInputStream(src);
            //根据源图片输入流获得ImageInputStream流
            ImageInputStream iis = ImageIO.createImageInputStream(in);
            //将ImageInputStream流加载到ImageReader中
            reader.setInput(iis, true);
            //图片读取参数
            ImageReadParam param = reader.getDefaultReadParam();

            Rectangle rect = new Rectangle(x, y, getImgWidth(new File(src)), getImgHeight(new File(src)));
            //参数对象设置形状为一定大小的长方形
            param.setSourceRegion(rect);
            //ImageReader根据参数对象获得BufferedImage
            BufferedImage bi = reader.read(0, param);
            //将经过参数对象筛选的图片流写入目标文件中
            ImageIO.write(bi, "png", new File(dest));
        }catch (IOException e){
            System.err.println("裁剪图片失败");
        }
    }
    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    /**
     * 获取图片高度
     * @param file  图片文件
     * @return 高度
     */
    public static int getImgHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getHeight(null); // 得到源图高
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}

maven

<!-- 这是excel的 -->
<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>19.9</version>
        </dependency>

word包jar包
https://pan.baidu.com/s/1Jp2UT4SaLXHYdK0GRPIQUQ

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值