Java实现office转PDF文件支持全部转换及Excel转换乱码和格式错乱解决

本人用的时springboot + LiberOffice ,根据需要进行代码调整

1、所需软件:LiberOffice,可到管网下载,它支持Linux与Owindows系统,挺好用

官网地址:下载 LibreOffice | LibreOffice 简体中文官方网站 - 自由免费的办公套件

百度网盘地址:链接:https://pan.baidu.com/s/1R7IV4gSv_Lb8vC0avr3yqA 
                         提取码:x5x9

2、pom依赖

 <!--office to pdf-->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>

3、文件配置 

jodconverter.local.office-home=是liberOffice的安装路径,安装路径要求无空格及中文字符

jodconverter.local.port-numbers是liberOffice的端口,可自定义

jodconverter.local.max-tasks-per-process 处理最大线程数,建议不要太大

jodconverter.local.enabled=true
jodconverter.local.office-home=D:/LibreOffice
jodconverter.local.port-numbers=8100
jodconverter.local.max-tasks-per-process=5

4、pdf转换方法

先注入一下

 @Resource
    private DocumentConverter converter;

    /**
     * 生成pdf预览文件
     **/
    @Override
    public void createPdf(String docPath,String pdfPath) throws Exception {
        
        File file = new File(docPath);
        InputStream in = new FileInputStream(file);
        String pdfFilePath = pdfPath + XXXXXXXXX + ".pdf";
        switch (suffix) {
            case "xls":
            case "xlsx":
            case "csv":
                ExcelToPDFUtil.excel2pdf(docPath, pdfFilePath);
                break;
            case "doc":
                File pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.DOC).to(pdfOutFile).execute();
                break;
            case "docx":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.DOCX).to(pdfOutFile).execute();
                break;
            case "ppt":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.PPT).to(pdfOutFile).execute();
                break;
            case "pptx":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.PPTX).to(pdfOutFile).execute();
                break;
            case "txt":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.TXT).to(pdfOutFile).execute();
                break;
            case "pdf":
                CopyFileUtil.copyFileToPath(docPath, pdfFilePath);
                break;
            case "html":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.HTML).to(pdfOutFile).execute();
                break;
            case "rtf":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.RTF).to(pdfOutFile).execute();
                break;
            case "swf":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.SWF).to(pdfOutFile).execute();
                break;
            case "svg":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.SVG).to(pdfOutFile).execute();
                break;
            case "png":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.PNG).to(pdfOutFile).execute();
                break;
            case "jpg":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.JPEG).to(pdfOutFile).execute();
                break;
            case "tif":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.TIFF).to(pdfOutFile).execute();
                break;
            case "bmp":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.BMP).to(pdfOutFile).execute();
                break;
            case "gif":
                pdfOutFile = new File(pdfFilePath);
                converter.convert(in).as(DefaultDocumentFormatRegistry.GIF).to(pdfOutFile).execute();
                break;
            default:
                break;
        }

       
    }

5、Excel转换pdf时,由于使用LiberOffice会导致格式错乱,就使用了一个插件,插件jar包与监听文件都在百度网盘的excel转pdf压缩包内,可以使用

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

public class ExcelToPDFUtil {

    public static void main(String[] args) throws Exception {
//        String sourceFilePath="d:/文件.xlsx";
//        String desFilePath="d:/文件.pdf";
//        excel2pdf(sourceFilePath, desFilePath);

    }

    /**
     * 获取license 去除水印
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = ExcelToPDFUtil.class.getClassLoader().getResourceAsStream("license/license-excel.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * excel 转为pdf 输出。
     *
     * @param sourceFilePath  excel文件
     * @param desFilePathd  pad 输出文件目录
     */
    public static void excel2pdf(String sourceFilePath, String desFilePathd ) throws Exception {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        Workbook wb = null;
        FileOutputStream fileOS = null;
        try {

            wb = new Workbook(sourceFilePath);// 原始excel路径
            int[] showSheets= new int[wb.getWorksheets().getCount()] ;
            fileOS = new FileOutputStream(desFilePathd);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
//            int[] autoDrawSheets={3};
//            autoDraw(wb,autoDrawSheets);

            //根据sheet页进行绘制。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }finally {
           if(fileOS != null){
               fileOS.flush();
               fileOS.close();
               fileOS = null;
           }
           if(wb != null){
               wb = null;
           }
        }
    }


    /**
     * 设置打印的sheet 自动拉伸比例
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb,int[] page){
        if(null!=page&&page.length>0){
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }


    /**
     * 隐藏workbook中不需要的sheet页。
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb,int[] page){
        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if(null==page||page.length==0){
            wb.getWorksheets().get(0).setVisible(true);
        }else{
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

}


6、由于pdf不需要转换,直接重写即可

public class CopyFileUtil {

    /**
     * 输入文件路径
     *
     * @param oldPath
     * @param newPath
     * @throws IOException
     */
    public static void copyFileToPath(String oldPath, String newPath) throws IOException {
//获取要复制的文件
        File oldfile = new File(oldPath);
//文件输入流,用于读取要复制的文件
        FileInputStream fileInputStream = new FileInputStream(oldfile);
//要生成的新文件(指定路径如果没有则创建)
        File newfile = new File(newPath);
//获取父目录
        File fileParent = newfile.getParentFile();
//判断是否存在
        if (!fileParent.exists()) {
// 创建父目录文件夹
            fileParent.mkdirs();
        }
//判断文件是否存在
        if (!newfile.exists()) {
//创建文件
            newfile.createNewFile();
        }

//新文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(newfile);
        byte[] buffer = new byte[1024];
        int len;
//将文件流信息读取文件缓存区,如果读取结果不为-1就代表文件没有读取完毕,反之已经读取完毕
        while ((len = fileInputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
            fileOutputStream.flush();
        }
        fileInputStream.close();
        fileOutputStream.close();

    }

}

故此完美转换pdf

7、在linux下转换pdf后如果出现乱码,则需安装中文支持包,可自行百度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值