Java使用Aspose实现office文件转PDF(20.7)

2,083 阅读2分钟

最近一直在弄在线教学平台,然后就需要实现在线预览文件功能.之前资源库一直用的libreoffice实现OfficePDF.但是libreoffice是单线程的,作为一个在线教学平台显然是不靠谱的.所以今天分享另一个纯Java实现OfficePDF工具Aspose

  • 首先我们先引入响应的pom配置(由于默认maven仓库下不下来.文末提供下载地址)
<dependency>
   <groupId>com.aspose</groupId>
   <artifactId>aspose-words</artifactId>
   <version>20.7</version>
   <classifier>jdk17</classifier>
</dependency>
<dependency>
   <groupId>com.aspose</groupId>
   <artifactId>aspose-slides</artifactId>
   <version>20.7</version>
   <classifier>jdk16</classifier>
</dependency>
<dependency>
   <groupId>com.aspose</groupId>
   <artifactId>aspose-cells</artifactId>
   <version>20.7</version>
</dependency>

采用工厂模式进行office系列转换

  • 新建接口而IFileConvert
public interface IFileConvert {

   /**
    * pdf文件后缀
    */
   String FILE_PDF_SUFFIX = ".pdf";

   default String getResultPath(String filePath, String fileSuffix){
       // 什么将要返回的pdf路径
       int i = filePath.lastIndexOf(".");
       String path = filePath.substring(0, i);
       return path + fileSuffix;
   }
   
   String fileToPdf(String filePath);
}
  • 实现WORD文件转换,新建WordsFileConvert
public class WordsFileConvert implements IFileConvert {

   private boolean getLicense() {
       boolean result = false;
       InputStream is = null;
       try {
           ClassLoader loader = Thread.currentThread().getContextClassLoader();
           is = loader.getResourceAsStream("license.xml");
           License license = new License();
           license.setLicense(is);
           result = true;
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (is != null) {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return result;
   }

   @Override
   public String fileToPdf(String filePath) {
   	//去除水印
       if (!getLicense()) {
           return null;
       }
       String pdfPath = null;
       FileOutputStream os = null;
       try {
           pdfPath = getResultPath(filePath, FILE_PDF_SUFFIX);
           os = new FileOutputStream(pdfPath);
           Document doc = new Document(filePath);
           doc.save(os, SaveFormat.PDF);
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (os != null) {
               try {
                   os.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return pdfPath;
   }
}
  • 实现PPT文件转换,新建SlidesFileConvert
public class SlidesFileConvert implements IFileConvert {

   private boolean getLicense() {
       boolean result = false;
       InputStream is = null;
       try {
           ClassLoader loader = Thread.currentThread().getContextClassLoader();
           is = loader.getResourceAsStream("license.xml");
           License license = new License();
           license.setLicense(is);
           result = true;
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (is != null) {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return result;
   }

   @Override
   public String fileToPdf(String filePath) {
       if (!getLicense()) {
           return null;
       }
       String pdfPath = null;
       FileOutputStream os = null;
       try {
           pdfPath = getResultPath(filePath, FILE_PDF_SUFFIX);
           os = new FileOutputStream(pdfPath);
           Presentation pres = new Presentation(filePath);
           pres.save(os, SaveFormat.Pdf);
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (os != null) {
               try {
                   os.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return pdfPath;
   }
}
  • 实现EXCEL文件转换,新建CellsFileConvert
public class CellsFileConvert implements IFileConvert {

   private boolean getLicense() {
       boolean result = false;
       InputStream is = null;
       try {
           ClassLoader loader = Thread.currentThread().getContextClassLoader();
           is = loader.getResourceAsStream("license.xml");
           License license = new License();
           license.setLicense(is);
           result = true;
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (is != null) {
               try {
                   is.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return result;
   }

   @Override
   public String fileToPdf(String filePath) {
       if (!getLicense()) {
           return null;
       }
       String pdfPath = null;
       FileOutputStream os = null;
       try {
           pdfPath = getResultPath(filePath, FILE_PDF_SUFFIX);
           os = new FileOutputStream(pdfPath);
           Workbook workbook = new Workbook(filePath);
           workbook.save(os, SaveFormat.PDF);
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           if (os != null) {
               try {
                   os.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return pdfPath;
   }
}
  • resources目录下新建license.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<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>
  • 新建工厂枚举FileConvertEnum
public enum FileConvertEnum {

    PPT("PPT", new SlidesFileConvert()),
    WORD("WORD", new WordsFileConvert()),
    EXCEL("EXCEL", new CellsFileConvert()),
    ;

    private String fileFormat;
    private IFileConvert fileConvert;

    FileConvertEnum(String fileFormat, IFileConvert fileConvert) {
        this.fileFormat = fileFormat;
        this.fileConvert = fileConvert;
    }

    public String getFileFormat() {
        return fileFormat;
    }

    public IFileConvert getFileConvert() {
        return fileConvert;
    }

    public static IFileConvert getFileConvert(String fileFormat) {
        for (FileConvertEnum fileConvertEnum : values()) {
            if (fileConvertEnum.fileFormat.equals(fileFormat)){
                return fileConvertEnum.fileConvert;
            }
        }
        return null;
    }
}
  • 使用方式
public static void main(String[] args) {
	IFileConvert fileConvert = FileConvertEnum.getFileConvert("WORD");
	String pdfUri = fileConvert.fileToPdf("/home/abelethan/Desktop/test.doc"); 
}