aspose pdf、excel、word、ppt转图片上传oss

背景:安卓手机没办法预览标题的几个基本文件类型,只能先转成图片之后再上传至阿里云。这边使用了aspose上传。

一、引入jar依赖

链接: https://pan.baidu.com/s/1IGQMRj6XSgtsUpz7oQNdyA 提取码: 53cy 复制这段内容后打开百度网盘手机App,操作更方便哦
<dependency>
   <groupId>com.aspose</groupId>
   <artifactId>aspose-words</artifactId>
   <version>15.8.0</version>
   <scope>system</scope>
   <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
<dependency>
   <groupId>com.aspose</groupId>
   <artifactId>aspose-cells</artifactId>
   <version>8.5.2</version>
   <scope>system</scope>
   <systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
</dependency>
<dependency>
   <groupId>aspose.slides</groupId>
   <artifactId>slides</artifactId>
   <version>15.9.0</version>
   <scope>system</scope>
   <systemPath>${project.basedir}/src/main/resources/lib/aspose.slides-15.9.0.jar</systemPath>
</dependency>

 二、工具类

这边将每个基本类型都整成一个方法了。

public class OssTypeUtlis {
    public static void main(String[] args) {

        //word2pdf("C:/Users/Administrator/Desktop/1.doc","C:/Users/Administrator/Desktop/xxxx.pdf");//word转pdf
        //word转图片格式
        try {
            String path = "C:/Users/John/Desktop/1.pdf";
            File file = new File(path);
            InputStream inStream = new FileInputStream(file);
            List<BufferedImage> wordToImg = pdfToimg(inStream);//
            BufferedImage mergeImage = mergeImage(false, wordToImg);
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
            ImageIO.write(mergeImage, "jpg", new File("C:/Users/John/Desktop/1.jpg")); //将其保存在C:/imageSort/targetPIC/下

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @Description: 验证aspose.word组件是否授权:无授权的文件有水印标记
     */
    public static boolean isWordLicense() {
        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>";
        boolean result = false;
        try {
            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;
    }

    public static boolean isPPTLicense() {
        boolean result = false;
        try {
            String s = "<License><Data><Products><Product>Aspose.Total 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.slides.License license = new com.aspose.slides.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean isExcelLicense() {
        boolean result = false;
        try {
            String s = "<License><Data><Products><Product>Aspose.Total 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.cells.License license = new com.aspose.cells.License();
            license.setLicense(inputStream);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Description: word和txt文件转换图片
     */
    public static List<BufferedImage> wordToImg(InputStream inputStream) {
        if (!isWordLicense()) {
            return null;
        }
        try {
            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 = ImageIO.createImageInputStream(parse(output));
                imageList.add(ImageIO.read(imageInputStream));
            }
            return imageList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @Description: ppt, pptx文件转换图片
     */
    public static List<BufferedImage> pptToimg(InputStream inputStream) {
        // 验证License
        if (!isPPTLicense()) {
            return null;
        }
        FileOutputStream out = null;
        try {
            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            Presentation pres = new Presentation(inputStream);
            ISlideCollection slides = pres.getSlides();
            for (int i = 0; i < slides.size(); i++) {
                ISlide slide = slides.get_Item(i);
                int height = (int) (pres.getSlideSize().getSize().getHeight() - 150);
                int width = (int) (pres.getSlideSize().getSize().getWidth() - 150);
                BufferedImage img = slide.getThumbnail(new java.awt.Dimension(width, height));
                imageList.add(img);
            }
            return imageList;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @Description: pdf文件转换图片
     */
    public static List<BufferedImage> pdfToimg(InputStream inputStream) {
        try {
            PDDocument pdDocument;
            pdDocument = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            /* dpi越大转换后越清晰,相对转换速度越慢 */
            int pages = pdDocument.getNumberOfPages();
            List<BufferedImage> imageList = new ArrayList<BufferedImage>();
            for (int i = 0; i < pages; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 300);
                imageList.add(image);
            }
            return imageList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @Description: excel文件转换图片
     */
    public static List<BufferedImage> excelToImg(InputStream inputStream) {
        if (!isExcelLicense()) {
            return null;
        }
        Workbook book = null;
        List<BufferedImage> imageList = new ArrayList<BufferedImage>();
        try {
            book = new Workbook(inputStream);
            WorksheetCollection worksheets = book.getWorksheets();
            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
            imgOptions.setImageFormat(ImageFormat.getJpeg());
            imgOptions.setCellAutoFit(true);
            imgOptions.setOnePagePerSheet(true);
            for (int i = 0; i < worksheets.getCount(); i++) {
                Worksheet sheet = worksheets.get(i);
                OutputStream output = new ByteArrayOutputStream();
                sheet.getPageSetup().setLeftMargin(-20);
                sheet.getPageSetup().setRightMargin(0);
                sheet.getPageSetup().setBottomMargin(0);
                sheet.getPageSetup().setTopMargin(0);
                SheetRender render = new SheetRender(sheet, imgOptions);
                render.toImage(0, output);
                ByteArrayInputStream parse = parse(output);
                if (parse != null) {
                    ImageInputStream imageInputStream = ImageIO.createImageInputStream(parse);
                    BufferedImage bufferedImage = ImageIO.read(imageInputStream);
                    imageList.add(bufferedImage);
                    parse.close();
                }
                output.close();
            }
            return imageList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

    /**
     * @Description: outputStream转inputStream
     */
    public static ByteArrayInputStream parse(OutputStream out) {
        try {
            ByteArrayOutputStream baos = null;
            baos = (ByteArrayOutputStream) out;
            ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            return swapStream;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }


    /**
     * 合并任数量的图片成一张图片
     *
     * @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();
            allh += img.getHeight();
            allhMax = Math.max(img.getHeight(), allhMax);
            allwMax = Math.max(img.getWidth(), allwMax);
        }
        // 创建新图片
        if (isHorizontal) {
            destImage = new BufferedImage(allw, allhMax, BufferedImage.TYPE_INT_RGB);
        } else {
            destImage = new BufferedImage(allwMax, allh + imgs.size() * 5, 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;
    }
}

 具体的上传阿里云代码:

     List<BufferedImage> imageList = new ArrayList<>();
            if (suffixname.endsWith(".xlsx") || suffixname.endsWith(".xls")) {
                imageList = OssTypeUtlis.excelToImg(file.getInputStream());
            } else if (suffixname.endsWith(".ppt") || suffixname.endsWith(".pptx")) {
                imageList = OssTypeUtlis.pptToimg(file.getInputStream());
            } else if (suffixname.endsWith(".pdf")) { //pdf
                imageList = OssTypeUtlis.pdfToimg(file.getInputStream());
            } else if (suffixname.endsWith(".doc") || suffixname.endsWith(".docx")) {
                imageList = OssTypeUtlis.wordToImg(file.getInputStream());
            }
            if (!CollectionUtils.isEmpty(imageList)) {
                BufferedImage mergeImage = OssTypeUtlis.mergeImage(false, imageList);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(mergeImage, "jpg", baos);
                inputStream = OssTypeUtlis.parse(baos);
                MultipartFile multipartFile = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
                PutObjectResult result = ossClient.putObject(newBucket, filePath, multipartFile.getInputStream());
                   filePath = "https://" + newBucket + "." + endPoint + SymbolConstant.SINGLE_SLASH + filePath;
                if (result != null) {
                    log.info("------OSS文件上传成功------" + fileUrl);
                }
            }

三、字体包问题

如果只是在windows环境下,是没有问题的,但是要是服务器是linux下面,就会出现中文乱码的情况。这样就需要在linux环境下去添加字体包。

贴一个之前看的博客。亲测有效。

Linux安装字体 java生成pdf中文乱码或提示未安装字体错误 - 独自一人的江湖 - 博客园

 记录一下,免得忘记了~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值