sts使用aspose实现Word转图片

本文档详细介绍了如何使用Aspose库将Word文档转换为图片,包括下载Aspose.jar包,创建Maven项目,设置依赖,编写转换代码,并提供了遇到问题时的解决方案。通过实例代码演示了转换过程,适合初学者参考。
摘要由CSDN通过智能技术生成

近期项目需要用到Word转图片的业务

查看了很多网站博客 在这期间还是踩了很多坑 新手刚上路 

就自己整理了一份

用这博客来激励一下自己  也再次感谢CSDN的各位大佬教会我很多新东西

因为本人是新手  所以写的教程可能会比较接近小白一点 (话不多说 开始整活 )

使用aspose的话首先我们要有aspose的架包  这个架包在网上找了好久

链接:https://pan.baidu.com/s/1gnqdHh0cZb8f_5guWgFxew
提取码:demo

下载好以后你会看到  以下文件

 然后就是新建maven项目了 我这里使用 SpringToolSuite方式 创建比较简单易懂

如果已经非常熟练请跳过该步骤

SpringToolSuite创建

 点击file 根据以下提示

然后会跳到这个页面  按如下操作

 下一步

 

 创建完成以后 会有一个MyDemo项目

 打开项目 创建一个类

 填写包名和 实体类名称

创建完实体类以后 

就是把上面我们下载好的架包复制到项目里面   (这里先放到实体类同级 方便理解)

 

 然后 就是选中jar包  右键 按照如下操作

 完成以后 如下图

然后就是重点了 把下面代码复制到刚刚我们创建的PdfDemo实体类中 (大佬们可以直接用这个)

package yu;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
 
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
 
import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
 
 
public class YuCe {
    public static void main(String[] args){
        //word2pdf("C:/Users/Administrator/Desktop/1.doc","C:/Users/Administrator/Desktop/xxxx.pdf");//word转pdf
        //word转图片格式
        try {
            File file = new File("D:/DemoFile/demo.docx");
 
            InputStream inStream = new FileInputStream(file);
            List<BufferedImage> wordToImg = wordToImg(inStream);//
            BufferedImage mergeImage = mergeImage(false, wordToImg);
 
            ImageIO.write(mergeImage, "jpg", new File("D:/DemoFile/8888.jpg")); //将其保存在C:/imageSort/targetPIC/下
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    
 
    /**
     * @Description: 验证aspose.word组件是否授权:无授权的文件有水印标记
     */
    public static boolean isWordLicense() {
        boolean result = false;
        try {
            String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes());
            com.aspose.words.License license = new com.aspose.words.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
 
    
    
    /**
     * @Description: word和txt文件转换图片
     */
    private static List<BufferedImage> wordToImg(InputStream inputStream) throws Exception {
        if (!isWordLicense()) {
            return null;
        }
        try {
            long old = System.currentTimeMillis();
            Document doc = new Document(inputStream);
            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);
            options.setPrettyFormat(true);
            options.setUseAntiAliasing(true);
            options.setUseHighQualityRendering(true);
            int pageCount = doc.getPageCount();
            
            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            for (int i = 0; i < pageCount; i++) {
                OutputStream output = new ByteArrayOutputStream();
                options.setPageIndex(i);
                doc.save(output, options);
                ImageInputStream imageInputStream = javax.imageio.ImageIO.createImageInputStream(parse(output));
                imageList.add(javax.imageio.ImageIO.read(imageInputStream));
 
            }
            return imageList;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
 
    //outputStream转inputStream
    public static ByteArrayInputStream parse(OutputStream out) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos = (ByteArrayOutputStream) out;
        ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
        return swapStream;
    }
 
    
 
    /**
     * 合并任数量的图片成一张图片
     *
     * @param isHorizontal true代表水平合并,fasle代表垂直合并
     * @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.LIGHT_GRAY);
        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];
            ImageArrayOne = img.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行扫描图像中各个像素的RGB到数组中
            if (isHorizontal) { // 水平方向合并
                destImage.setRGB(wx, 0, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            } else { // 垂直方向合并
                destImage.setRGB(0, wy, w1, h1, ImageArrayOne, 0, w1); // 设置上半部分或左半部分的RGB
            }
            wx += w1;
            wy += h1 + 5;
        }
 
 
        return destImage;
    }
 
 
    
    
    public static void word2pdf(String docPath,String savePath){
 
        try {
        String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
        ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
        License license = new License();
        license.setLicense(is);
        com.aspose.words.Document document = new com.aspose.words.Document(docPath);
        document.save(new FileOutputStream(new File(savePath)),SaveFormat.PDF);
        } catch (Exception e) {
            
            e.printStackTrace();
        }
    }
        
}

复制进去以后 一般情况下会出现两个错误  需要我们修改  (此处模拟了一下错误 本来我应该把提供的代码块改成我们这次创建的实体类名称和包名称的 )

 然后在我们的本地创建一个新的文件夹 放一个word文档  (我这里用的是D盘)注意这个文件路径下面会用到

 然后修改我们代码块里面的 文件路径和要保存的路径

 修改完成以后 在选中实体类中空白处 鼠标右键

执行一下  出现下面情况则说明转换成功 

 到这里 我们 的word转图片就大功告成了 

(老婆镇贴)

最后 祝愿所有看到这篇博客的 陌生人 写代码永无BUG  职场之路风声水起  让我们一起努力 共同进步吧

有很多的不快乐,其实是源自不满足,而不满足,很多时候是源自于心不定,而心不定则是因为不清楚究竟自己要什么,不清楚要什么的结果就是什么都想要,结果什么都没得到

所以我们要明白当前自己需要什么 

我是一个职场新人 开发小白一枚 感谢您的支持

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值