1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
public static java.util.List<String> convertPng(File file, File outputFolder, String newFileName) throws Exception { // TODO 校验输入文件是否存在 以及是否为PPT java.util.List<String> newFileList = Lists.newArrayList(); try { if (!outputFolder.exists()) { outputFolder.mkdirs(); } if (StringUtils.isBlank(newFileName)) { newFileName = UUID.randomUUID().toString().replace("-", "")+"_"; } String newFilePath = null; FileInputStream is = new FileInputStream(file); HSLFSlideShow ppt = new HSLFSlideShow(is); is.close(); Dimension pgsize = ppt.getPageSize(); int idx = 1; for (HSLFSlide slide : ppt.getSlides()) { //防止中文乱码 for(HSLFShape shape : slide.getShapes()){ if(shape instanceof HSLFTextShape) { HSLFTextShape tsh = (HSLFTextShape)shape; for(HSLFTextParagraph p : tsh){ for(HSLFTextRun r : p){ r.setFontFamily("宋体"); } } } } newFilePath = outputFolder.getAbsolutePath() + "/" + newFileName + idx + ".png"; File newFile = new File(newFilePath); if (newFile.exists()) { newFile.delete(); } System.out.println("正在处理PPT TO PNG, page=" + idx); BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); // clear the drawing area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); // render slide.draw(graphics); // save the output FileOutputStream out = new FileOutputStream(newFilePath); javax.imageio.ImageIO.write(img, "png", out); out.close(); System.out.println("处理完成PPT TO PNG, page=" + idx); newFileList.add(newFilePath); idx++; } } catch (FileNotFoundException e) { throw new RuntimeException("没有找到相应的文件"); } catch (IOException e) { throw new RuntimeException("系统出现IO异常,无法继续处理"); }catch (OfficeXmlFileException e){ throw new RuntimeException("请使用2003, 2007的格式PPT"); }catch (Exception e){ e.printStackTrace(); throw new RuntimeException("请使用2003, 2007的格式PPT"); } return newFileList; } |