java利用第三方jar实现excel,word,ppt,txt转pdf格式

最近项目有文件模块的上传预览功能,比如把word文档上传,以后点击可以预览。采用的思路为:文件上传到服务器,然后获取转换成对应的新的PDF文件,然后读取PDF文件。本文着重实现文档上传然后转为PDF。所需jar:   链接:https://pan.baidu.com/s/1-CX_QRy88Y-giHuhj0Lc_Q 
提取码:t2rn

如果遇到利用aspose 把excel转pdf遇到复杂文件被拆分成多页的情况,添加如下代码:

 PdfSaveOptions pOptions = new PdfSaveOptions();
 pOptions.setAllColumnsInOnePagePerSheet(true);
 excel.save(destFilePath,pOptions);

文件上传代码:

复制代码

    public String fileUpload(HttpServletRequest request, HttpServletResponse response) {

        String saveDirectory = request.getServletContext().getRealPath("/upload");//上传路径
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            String extName = "";// 扩展名
            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    try {
                        InputStream is = file.getInputStream();
               //获取文件md5值判断是否有重复,如果有文件就不上传,直接读取
                        String fileHashCode = MD5Util.md5HashCode32(is);
                        String originalFileName = file.getOriginalFilename();
               //获取扩展名
                        extName = originalFileName.substring(originalFileName.lastIndexOf("."));
                        //源文件上传地址
               String sourceFilePath = saveDirectory + File.separator + fileHashCode + extName;
               //生成的目标文件地址
                        String destinatFilePath = request.getServletContext.getRealPath("/convert")+File.separator+fileHashCode + ".pdf";
              // 表示文件已存在不需要上传
               if (new File(sourceFilePath).exists()) { 
                  continue;//跳出本次循环

                        } else {
                            file.transferTo(new File(path));// 生成新的文件
                            file.getInputStream().close();//流关最好在finally里关闭
                            // 文件转换工具用于转换文件,最好新开线程,对文件较大的需要等待时间。参数(源文件路径,目标文件路径)
                            FileConvertUtils.convert(sourceFilePath, destinatFilePath);
                        }

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

            }
            return "请选择文件上传!";
        }
        return "文件上传请求配置错误!";

    }

复制代码

定义函数用于判断调用哪个转换函数:

复制代码

public class FileConvertUtils {
    public static final Logger log = LoggerFactory.getLogger(FileConvertUtils.class);

    public static void convert(final String sourceFilePath ,final String destFilePath){
        String fileType = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
        ExecutorService executor = Executors.newCachedThreadPool() ;
        executor.submit(() -> {
            try {
                //要执行的业务代码,
                  if(!"".equals(fileType)&&fileType!=null){
                      if(".doc".equals(fileType)||".docx".equals(fileType)||".wps".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".txt".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".xls".equals(fileType)||".xlsx".equals(fileType)){
                          OfficeToPdfUtils.excel2Pdf(sourceFilePath,destFilePath);
                      }else if(".ppt".equals(fileType)||".pptx".equals(fileType)){
                          OfficeToPdfUtils.ppt2Pdf(sourceFilePath,destFilePath);
                      }else if(".pdf".equals(fileType)){
                          FileUtils.copyFile(sourceFilePath, destFilePath);
                      }
                  }
            }catch(Exception e) {
                e.printStackTrace();
                throw new RuntimeException("报错啦!!");
            }

        });

    }

   
}

复制代码

 

文件转换核心代码:

复制代码

package com.hhwy.fileview.convert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aspose.cells.Workbook;
import com.aspose.pdf.SaveFormat;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.hhwy.fweb.framework.api.utils.IoTools;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.*;

public class OfficeToPdfUtils {

    /**
     * The constant LOG.
     *
     */
    private static final Logger LOG = LoggerFactory.getLogger(OfficeToPdfUtils.class);

    /**
     * 获取license
     *
     * @return
     */
    public static boolean getWordLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路径,这里我引用的是公司的包获取路径,这边自己可以定义指定路径
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static boolean getPPTLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路径
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            InputStream license = new FileInputStream(new File(IoTools.getABSPATH() + "WEB-INF/license.xml"));// license路径
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(license);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void word2Pdf(String resourceFilePath, String destFilePath) {
        InputStream wordIn = null;
        try {
             wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 验证License
        if (!getWordLicense()) {
            LOG.error("验证License失败!");
            return;
        }
        try {
            Document doc = new Document(wordIn);
            fileOS = new FileOutputStream(new File(destFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }
    public static void ppt2Pdf(String resourceFilePath, String destFilePath){
        InputStream wordIn = null;
        try {
            wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 验证License
        if (!getPPTLicense()) {
            LOG.error("验证License失败!");
            return;
        }
        try {
            fileOS = new FileOutputStream(new File(destFilePath));
            Presentation ppt = new Presentation(wordIn);
        //此处不可写SaveFormat.Pdf,这样转换能生成文件,但是转换的文件无法打开
            ppt.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }

   
    public static void word2Html(String resourceFilePath, String destFilePath) {
        InputStream wordIn = null;
        try {
             wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 验证License
        if (!getWordLicense()) {
            LOG.error("验证License失败!");
            return;
        }
        try {
            Document doc = new Document(wordIn);
            fileOS = new FileOutputStream(new File(destFilePath));
            // 保存转换的pdf文件
            doc.save(fileOS, com.aspose.words.SaveFormat.HTML);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }
    public static void excel2Pdf(String resourceFilePath, String destFilePath){
        InputStream in = null;
        try {
            in = new FileInputStream(new File(resourceFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        // 验证License
        if (!getExcelLicense()) {
            LOG.error("验证License失败!");
            return;
        }
        try {
            fileOS = new FileOutputStream(new File(destFilePath));
            Workbook excel = new Workbook(in);
            excel.save(destFilePath,com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            LOG.error("error:", e);
        } finally {
            try {
                if(fileOS != null){
                    fileOS.close();
                    System.out.println("转换已完成!");
                }
            } catch (IOException e) {
                LOG.error("error:", e);
            }
        }
    }

    public static void main(String[] args) {
            word2Pdf("/Users/workspace/docs/test.docx","/Users/workspace/docs/test.pdf");

          /*  InputStream pptIn = new FileInputStream(new File("/Users/workspace/docs/test.pptx"));
            ppt2Pdf(pptIn,"/Users/workspace/docs/test-ppt.pdf");

            InputStream excelIn = new FileInputStream(new File("/Users/workspace/docs/test.xlsx"));
            excel2Pdf(excelIn,"D:\\aspose\\test-excel.pdf");

            InputStream txtIn = new FileInputStream(new File("/Users/workspace/docs/test.txt"));
            word2Pdf(txtIn,"/Users/workspace/docs/test-txt.pdf");*/

    }
}

复制代码

本在实现上还有许多需要优化的地方,比如如何得知某文件何时转换成功,文件夹,文件不存在时候的判断等。后续优化后再更新。

针对无法获取文件何时转换成功,修改了FileConvertUtils 使其实现Callable接口,定义线程池在上传文件外部调用该类,代码:

复制代码

public class FileConvertUtils implements Callable<Integer>{

    private String sourceFilePath;
    private String destFilePath;
    
    FileConvertUtils(String sourceFilePath,String destFilePath){
        this.sourceFilePath = sourceFilePath;
        this.destFilePath = destFilePath;
    }
    
    public void convert(String sourceFilePath,String destFilePath){
        String fileType = sourceFilePath.substring(sourceFilePath.lastIndexOf("."));
            try {
                //要执行的业务代码,
                  if(!"".equals(fileType)&&fileType!=null){
                      if(".doc".equals(fileType)||".docx".equals(fileType)||".wps".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".txt".equals(fileType)){
                          OfficeToPdfUtils.word2Pdf(sourceFilePath,destFilePath);
                      }else if(".xls".equals(fileType)||".xlsx".equals(fileType)){
                          OfficeToPdfUtils.excel2Pdf(sourceFilePath,destFilePath);
                      }else if(".ppt".equals(fileType)||".pptx".equals(fileType)){
                          OfficeToPdfUtils.ppt2Pdf(sourceFilePath,destFilePath);
                      }else if(".pdf".equals(fileType)){
                          FileUtils.copyFile(sourceFilePath, destFilePath);
                      }
                  }
            }catch(Exception e) {
                e.printStackTrace();
                throw new RuntimeException("报错啦!!");
            }      

    }

    @Override
    public Integer call() throws Exception {
        this.convert(sourceFilePath, destFilePath);
        return 1;//通过future.get可以获取改返回值,表示执行完成
    }

复制代码

调用处代码:

                            ExecutorService executor = Executors.newCachedThreadPool();
                            Future<Integer> future = executor.submit(new FileConvertUtils(sourceFilePath,destinatFilePath));
                            System.out.println("=================="+future.get());//如果返回1,则调用成功,否则get方法会一直阻塞。

 

增加ppt转图片操作方法:

复制代码

    /**
     * pptToImage
     * @param resourceFilePath
     * @param destFilePath
     */
    
    public static void ppt2Image(String resourceFilePath,String destFilePath){
        InputStream wordIn = null;
        try {
            wordIn = new FileInputStream(new File(resourceFilePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileOutputStream fileOS = null;
        //验证license
        if(!getPPTLicense()){
            LOG.error("验证License失败!");
            return;
        }
        try {
            Presentation ppt = new Presentation(wordIn);
            int i=0;
            for(;i<ppt.getSlides().size();i++){
                ISlide slide = ppt.getSlides().get_Item(i);
                int hight = (int) (ppt.getSlideSize().getSize().getHeight()-150);
                int width = (int) (ppt.getSlideSize().getSize().getWidth()-150);
                BufferedImage image = slide.getThumbnail(new Dimension(width,hight));
                //每页输出一张图片
                File outImage = new File(destFilePath.replace(".pdf","")+i+".JPG");
                ImageIO.write(image, "JPG", outImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

复制代码

destinatFilePath 
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,我们可以通过引入第三方JAR包来使用第三方库中的功能。要执行命令,我们可以使用Java中的`ProcessBuilder`类来创建一个新的进程,并在该进程中执行命令。 首先,我们需要将第三方JAR包添加到Java项目的构建路径中。这可以通过将JAR文件复制到项目的`lib`目录下,并在IDE中将其添加到构建路径中实现。 然后,我们需要使用`ProcessBuilder`类创建一个新的进程,并在该进程中执行命令。我们可以通过调用`start()`方法来启动这个新进程。 下面是一个简单的示例代码,展示了如何引入第三方JAR包并执行命令: ```java import java.io.IOException; public class ExecuteCommand { public static void main(String[] args) { try { // 创建ProcessBuilder对象,并将第三方JAR包的名称和要执行的命令作为参数 ProcessBuilder pb = new ProcessBuilder("java", "-jar", "third-party.jar", "command"); // 设置进程的工作目录(可选) pb.directory(new File("path/to/working/directory")); // 启动新进程 Process process = pb.start(); // 等待进程执行完毕并获取返回值 int exitCode = process.waitFor(); // 检查进程是否执行成功 if (exitCode == 0) { System.out.println("命令执行成功"); } else { System.out.println("命令执行失败"); } } catch (IOException | InterruptedException e) { System.out.println("命令执行发生异常: " + e.getMessage()); } } } ``` 在上面的代码中,我们使用`ProcessBuilder`类创建一个新的进程,并将第三方JAR包的名称和要执行的命令作为参数传递给这个进程。然后,我们可以通过调用`start()`方法来启动这个新进程,并使用`waitFor()`方法等待进程执行完毕并获取返回值。最后,我们可以根据返回值来判断命令是否执行成功。 需要注意的是,我们可以使用`directory()`方法设置进程的工作目录,这对于某些命令可能是必需的。 希望以上解答对您有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值