使用aspose进行将word转换为图片格式

项目为maven项目,因为使用的是破解版的aspose.jar包,所以使用引用外部jar包方式直接将包打入项目中build即可

将jar包引入项目中

将word文件路径与文件名传入saveImage方法 调用即可生成图片

   public String saveImage(String filePath, String fileName){

        //word2pdf("C:/Users/Administrator/Desktop/1.doc","C:/Users/Administrator/Desktop/xxxx.pdf");//word转pdf


        //word转图片格式
        try {
            File file = new File(filePath+fileName);
            System.out.println(filePath+fileName);
            InputStream inStream = new FileInputStream(file);

            Document doc = new Document(filePath+fileName);
            int pageCount = doc.getPageCount();
            System.out.println(pageCount);
            List<BufferedImage> wordToImg = wordToImg(inStream,pageCount+2);//
            BufferedImage mergeImage = mergeImage(false, wordToImg);
            String imgPath = "D:/ruoyi/uploadPath/avatar/" +UUID.randomUUID()+".png";
            ImageIO.write(mergeImage, "jpg",new File( imgPath));
            try {
                inStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            return imgPath;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
  /**
     * @Description: word和txt文件转换图片
     */
    private static List<BufferedImage> wordToImg(InputStream inputStream, int pageNum) 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();
            if (pageCount > pageNum) {//生成前pageCount张
                pageCount = pageNum;
            }
            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;
    }

也可以将word直接转换为pdf输出,将pdf转换为图片。本项目中暂不采取这种措施,因为来回发生效率问题

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();
        }
    }

如需jar包可前往云盘下载

[网盘链接](https://pan.baidu.com/s/1GmIo9EzwpB2kFIQELZtLGw)

提取码:5fba

如果对您有帮助请点个关注

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Aspose.Words for .NET提供了将Word文档中的内容转换图片的功能,可以使用以下代码将Word文档转换图片并调整图片格式列宽: ```csharp // 加载Word文档 Document doc = new Document("input.docx"); // 创建ImageSaveOptions对象 ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); // 设置图片格式列宽 options.HorizontalResolution = 200; options.VerticalResolution = 200; // 遍历文档中的每个页面,并将其转换图片 for (int pageIndex = 0; pageIndex < doc.PageCount; pageIndex++) { // 创建MemoryStream对象 MemoryStream stream = new MemoryStream(); // 将当前页面保存为图片 doc.Save(stream, options); // 加载图片 Image image = Image.FromStream(stream); // 调整图片格式列宽 int newWidth = image.Width * 2; int newHeight = image.Height * 2; // 创建新的Bitmap对象 Bitmap newBitmap = new Bitmap(newWidth, newHeight); // 创建Graphics对象 Graphics graphics = Graphics.FromImage(newBitmap); // 绘制图像 graphics.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel); // 保存图片 newBitmap.Save("output.png", ImageFormat.Png); // 释放资源 stream.Dispose(); image.Dispose(); graphics.Dispose(); newBitmap.Dispose(); } ``` 在上述代码中,我们使用了ImageSaveOptions对象来设置生成的图片的格式,包括水平分辨率和垂直分辨率。然后,我们遍历文档中的每个页面,并将其转换图片。对于每个页面,我们先将其保存为MemoryStream对象,然后将其加载为Image对象。接着,我们根据需要调整图片的格式列宽,然后创建新的Bitmap对象,并使用Graphics对象将原始图像绘制到新的Bitmap对象中。最后,我们保存新的Bitmap对象为PNG格式的图片

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值