word转pdf后续(三)

2,830 阅读2分钟

之前的转pdf的方法功能局限性太高,只能转换docx格式而且表格内的内容容易丢失数据。导致后面又花了时间去做了优化。这个方法优势是doc和docx格式的文档都可以转换,缺点就是会需要生成中间的临时文件,占用了额外的io资源。因为我的业务是需要将pdf上传到文件服务器上而不是本地。假如是保存到本地的话就没事了。

使用的是aspose的破解包,这个包版本不一样,license也会不一样。

依赖

    <!-- https://mvnrepository.com/artifact/com.aspose.words/aspose-words-jdk16 -->
    <dependency>
        <groupId>com.aspose.words</groupId>
        <artifactId>aspose-words-jdk16</artifactId>
        <version>15.8.0</version>
    </dependency>  

aspose的document构造方法有多种
demo里用的是参数是路径的,我项目中是使用的参数是stream通过网络读取文件服务器上的文件转成输入流。

  • 无参: Document document = new Document()
  • 参数是路径: Document document = new Document(String fileName)
  • 参数是Stream: Document document = new Document(InputStream stream)

代码实现

package com.topdf.demo.demo.util;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;

public class Word2PdfUtil {



  /**
   * word转pdf
   * @param docPath 源文件
   * @param savePath 保存的pdf文件
   */
  public static void word2pdf(String docPath,String savePath){
      //aspose破解jar包license 不同的jar包对应不同的license
      String licenseStr = "<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 = null;
      FileOutputStream fos = null;
      try {
          is = new ByteArrayInputStream(licenseStr.getBytes());
          fos = new FileOutputStream(new File(savePath));
          License license = new License();
          license.setLicense(is);
          Document document = new Document(docPath);

          //会在本地生成一个pdf文件
          document.save(fos, SaveFormat.PDF);
      } catch (Exception e) {
          e.printStackTrace();
      }finally {
          try {
              if(is != null){
                  is.close();
              }
              if(fos != null){
                  fos.close();
              }
          }catch (Exception e){
              e.printStackTrace();
          }
      }
  }


  /**
   * 测试代码
   * @param args
   */
  public static void main(String[] args){
      //word转图片格式

      String srcPath = "C:\\Users\\hy\\Desktop\\测试.doc";
      String desPath = "D:\\测试.pdf";
      word2pdf(srcPath,desPath);
      System.out.println(Thread.currentThread()+"执行成功");

      //手动删除本地的pdf文件如果就是保存到本地的话可以不用删除
      File file = new File(desPath);
      if(file.exists()){
          boolean delete = file.delete();
          System.out.println(Thread.currentThread()+"删除返回"+delete);
      }

  }
}