Java实现Word/Excel/TXT转PDF

2020-01-15 09:28:33来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java实现Word/Excel/TXT转PDF

引言:

       前段时间公司做的教育系统,系统需要实时记录用户学习课程的情况和时间,所以对一些除视频课程之外,对一些文本文档型课件同样如此,初次的方案是讲office相关类型的文件进行转换Html文件,然后展示对应的html文件,PC端差不多没问题了,但是个别文件再转换html之后,样式出现了错乱,即时做了编码转换处理,但是还是有个别乱码,最后改变方案,最后统一将文件转为pdf,然后通过流的方式在前端展示,其中包括Word Excel PPT TXT PDF等文件,代码如下:

   备注:本来是可以直接展示pdf的,但是Andior上pdf展示不了,最后统一就用IO流的方式进行读取展示了.

1:添加maven依赖

<!--excel word txt ppt转pdf依赖-->
        <dependency>
            <groupId>aspose</groupId>
            <artifactId>pdf</artifactId>
            <version>11.5.0</version>
        </dependency>
        <dependency>
            <groupId>aspose</groupId>
            <artifactId>words</artifactId>
            <version>16.4.0</version>
        </dependency>
        <dependency>
            <groupId>aspose</groupId>
            <artifactId>cell</artifactId>
            <version>8.9.2</version>
        </dependency>
        <dependency>
            <groupId>aspose</groupId>
            <artifactId>pdf</artifactId>
            <version>11.5.0</version>
        </dependency>

2:添加license-excel.xml文件(Resource文件夹下)

<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>

3:代码如下:

  3.1获取License文件

 1 public static boolean getLicense(){
 2         boolean result = false;
 3         InputStream is =  null;
 4         try{
 5             
 6             is =UploadFiles.class.getClassLoader().getResourceAsStream("license-excel.xml");
 7             License aposeLic = new License();
 8             aposeLic.setLicense(is);
 9             result = true;
10         }catch(Exception e){
11             e.printStackTrace();
12         }finally{
13             try {
14                 is.close();
15             } catch (IOException e) {
16                 // TODO Auto-generated catch block
17                 e.printStackTrace();
18             }
19         }
20         return result;
21     }

 3.2:文本文件转码

 1   /* 将txt 转换编码
 2    * @param file
 3    * @author zsqing
 4   */
 5 public File saveAsUTF8(File file){
 6         String code = "gbk";
 7         byte[] head = new byte[3];
 8         try {
 9             InputStream inputStream = new FileInputStream(file);
10             inputStream.read(head);
11             if (head[0] == -1 && head[1] == -2) {
12                 code = "UTF-16";
13             } else if (head[0] == -2 && head[1] == -1) {
14                 code = "Unicode";
15             } else if (head[0] == -17 && head[1] == -69 && head[2] == -65) {
16                 code = "UTF-8";
17             }
18             inputStream.close();
19 
20             System.out.println(code);
21             if (code.equals("UTF-8")) {
22                 return file;
23             }
24             String str = FileUtils.readFileToString(file, code);
25             FileUtils.writeStringToFile(file, str, "UTF-8");
26             System.out.println("转码结束");
27         } catch (FileNotFoundException e) {
28             e.printStackTrace();
29         } catch (IOException e) {
30             e.printStackTrace();
31         }
32 
33         return file;
34     }

3.3:word和txt转换pdf

 1 /**
 2  * 将word txt转换成pdf
 3  * @param inPath
 4  * @param outPath
 5  * @author zsqing
 6 */
 7 public  void wordAndTextToPdf(String inPath, String outPath ,String localIP,HttpServletRequest request)
 8     {
 9         String fileToPdfUrl="";
10         boolean flag = false;
11         File file = null;
12         FileOutputStream os = null;
13         try
14         {
15             //long old = System.currentTimeMillis();
16             // 新建一个空白文档
17             file = new File(outPath);
18             file = saveAsUTF8(file);
19             os = new FileOutputStream(file);
20             // InPath是将要被转化的文档
21             com.aspose.words.Document doc = new com.aspose.words.Document(inPath);
22             /*
23              * 全面支持DOC,DOCX进行OOXML,RTF,HTML,OpenDocument,PDF,EPUB,XPS,SWF间转换
24              */
25             doc.save(os, SaveFormat.PDF);
26             flag = true;
27             //long now = System.currentTimeMillis();
28             //System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
29             
30         }
31         catch (Exception e)
32         {
33             e.printStackTrace();
34         }
35         finally
36         {
37             try
38             {
39                 if (os != null)
40                 {
41                     os.close();
42                 }
43             }
44             catch (Exception e)
45             {
46                 e.printStackTrace();
47             }
48             if (!flag)
49             {
50                 file.deleteOnExit();
51             }
52         }
53     }

3.4:Excel转换pdf

 1 /**
 2  * 将docx转换成pdf
 3  * @param inPath
 4  * @param outPath
 5  * @author zsqing
 6  */
 7  public  void wordToPdf(String inPath, String outPath ,String localIP,HttpServletRequest request)
 8     {
 9         String fileToPdfUrl="";
10         boolean flag = false;
11         File file = null;
12         FileOutputStream os = null;
13         try
14         {
15             //long old = System.currentTimeMillis();
16             // 新建一个空白文档
17             file = new File(outPath);
18             file = saveAsUTF8(file);
19             os = new FileOutputStream(file);
20             // InPath是将要被转化的文档
21             com.aspose.words.Document doc = new com.aspose.words.Document(inPath);
22             /*
23              * 全面支持DOC,DOCX进行OOXML,RTF,HTML,OpenDocument,PDF,EPUB,XPS,SWF间转换
24              */
25             doc.save(os, SaveFormat.PDF);
26             flag = true;
27             //long now = System.currentTimeMillis();
28             //System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
29             
30         }
31         catch (Exception e)
32         {
33             e.printStackTrace();
34         }
35         finally
36         {
37             try
38             {
39                 if (os != null)
40                 {
41                     os.close();
42                 }
43             }
44             catch (Exception e)
45             {
46                 e.printStackTrace();
47             }
48             if (!flag)
49             {
50                 file.deleteOnExit();
51             }
52         }
53     }

最近工作有些忙写的就少了,2020年第一篇与大家分享,一起学习,共同成长!


原文链接:https://www.cnblogs.com/zhaosq/p/12168046.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java调用WebService .net发布的接口

下一篇:HashMap、Hashtable、ConcurrentHashMap的原理与区别