专业的JAVA编程教程与资源

网站首页 > java教程 正文

java实现word、excel、ppt转pdf

temp10 2024-12-03 02:50:14 java教程 14 ℃ 0 评论

背景

本人通过Aspose实现word、excel、ppt转pdf。

包对应

word => Aspose-words-15.8.0.jar

java实现word、excel、ppt转pdf

excel => Aspose-cell-8.5.2.jar

ppt => Aspose-slides-19.3.jar

链接:https://pan.baidu.com/s/1Y1kkVPu9WpoaMwhjMV59UQ

提取码:24hx

实现

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 转pdf
 *
 * @author cnl
 */
@Slf4j
public class FileConverter {

    public static void main(String[] args) {
        String inputFile = "C:\\Users\\cnl\\Desktop\\test\\b.pptx";
        String outputFile = "C:\\Users\\cnl\\Desktop\\test\\cc\\output.pdf";
        convertToPdf(inputFile, outputFile);
    }

    /**
     * 获取 生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param sourceFilePath 原文件路径
     * @return 生成的 pdf 文件
     */
    private static String getPdfFilePath(String sourceFilePath) {
        return sourceFilePath.substring(0, sourceFilePath.lastIndexOf('.')) + ".pdf";
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName 文件路径
     * @return 返回文件后缀名
     */
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
            return "";
        }
        return fileName.substring(dotIndex + 1).toLowerCase();
    }

    /**
     * 创建文件父类的目录
     *
     * @param targetFilePath
     */
    private static void mkdir(String targetFilePath) {
        File file = new File(targetFilePath);
        if (file.getParentFile().exists()) {
            return;
        }

        file.getParentFile().mkdir();
    }

    /**
     * 转换pdf
     *
     * @param sourceFilePath 源文件路径
     * @return 返回pdf的文件路径
     */
    public static String convertToPdf(String sourceFilePath) {
        String pdfFilePath = getPdfFilePath(sourceFilePath);
        convertToPdf(sourceFilePath, pdfFilePath);
        return pdfFilePath;
    }

    /**
     * 转pdf
     *
     * @param sourceFilePath 源文件路径
     * @param pdfFilePath    生成pdf的路径
     */
    public static void convertToPdf(String sourceFilePath, String pdfFilePath) {
        String extension = getFileExtension(sourceFilePath);
        convertToPdf(sourceFilePath, pdfFilePath, extension);
    }

    /**
     * 转pdf
     *
     * @param sourceFilePath 源文件路径
     * @param sourceFileType 源文件类型
     * @param pdfFilePath    生成pdf的路径
     */
    public static void convertToPdf(String sourceFilePath, String sourceFileType, String pdfFilePath) {
        InputStream in = null;
        try {
            in = new FileInputStream(sourceFilePath);
        } catch (Exception e) {
            log.error("excelFilePath covert inputStream failed", e);
            e.printStackTrace();
        }

        convertToPdf(in, sourceFileType, pdfFilePath);
    }

    /**
     * 转pdf
     *
     * @param sourceIn       源文件流
     * @param sourceFileType 源文件类型
     * @param pdfFilePath    生成pdf的路径
     */
    public static void convertToPdf(InputStream sourceIn, String sourceFileType, String pdfFilePath) {
        switch (sourceFileType) {
            case "doc":
            case "docx":
                convertWordToPdf(sourceIn, pdfFilePath);
                break;
            case "ppt":
            case "pptx":
                convertPowerPointToPdf(sourceIn, pdfFilePath);
                break;
            case "xls":
            case "xlsx":
                convertExcelToPdf(sourceIn, pdfFilePath);
                break;
            default:
                throw new IllegalArgumentException("Unsupported file format");
        }
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    //+++++++++++++++++++++++++++++【wordToPdf】++++++++++++++++++++++++++++++++++//
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

    /**
     * word 转 pdf
     *
     * @param wordFilePath word 文件路径
     * @return 返回 pdf 文件路径
     */
    public static String convertWordToPdf(String wordFilePath) {
        String pdfFilePath = getPdfFilePath(wordFilePath);
        convertWordToPdf(pdfFilePath, pdfFilePath);
        return pdfFilePath;
    }

    /**
     * word 转 pdf
     *
     * @param wordFilePath word 文件路径
     * @param pdfFilePath  生成的 pdf 文件路径
     */
    public static void convertWordToPdf(String wordFilePath, String pdfFilePath) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        InputStream in = null;
        try {
            in = new FileInputStream(wordFilePath);
        } catch (Exception e) {
            log.error("excelFilePath covert inputStream failed", e);
            e.printStackTrace();
        }

        convertWordToPdfByIn(in, pdfFilePath);
    }


    /**
     * word 转 pdf
     *
     * @param sourceIn    word 流
     * @param pdfFilePath 生成的 pdf 文件路径
     */
    public static void convertWordToPdf(InputStream sourceIn, String pdfFilePath) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        convertWordToPdfByIn(sourceIn, pdfFilePath);
    }

    /**
     * word 转 pdf
     *
     * @param sourceIn    word 流
     * @param pdfFilePath 生成的 pdf 文件路径
     */
    private static void convertWordToPdfByIn(InputStream sourceIn, String pdfFilePath) {
        //检测与创建目标文件目录
        mkdir(pdfFilePath);

        // 验证 License
        getWordLicense();

        try (FileOutputStream os = new FileOutputStream(pdfFilePath)) {
            Document doc = new Document(sourceIn);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
            e.printStackTrace();
        }
    }


    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getWordLicense() {
        try (InputStream is = FileConverter.class.getClassLoader().getResourceAsStream("license-file.xml")) {
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    //+++++++++++++++++++++++++++++【excelToPdf】++++++++++++++++++++++++++++++++++//
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @return 返回pdf文件路径
     */
    public static String convertExcelToPdf(String excelFilePath) {
        String pdfFilePath = getPdfFilePath(excelFilePath);
        convertExcelToPdf(excelFilePath, pdfFilePath, null);
        return pdfFilePath;
    }

    /**
     * excel 转 pdf
     *
     * @param sourceIn excel 流
     */
    public static void convertExcelToPdf(InputStream sourceIn, String pdfFilePath) {
        convertExcelToPdf(sourceIn, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param convertSheets 需要转换的sheet
     * @return 返回pdf文件路径
     */
    public static String convertExcelToPdf(String excelFilePath, int[] convertSheets) {
        String pdfFilePath = getPdfFilePath(excelFilePath);
        convertExcelToPdf(excelFilePath, pdfFilePath, convertSheets);
        return pdfFilePath;
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     */
    public static void convertExcelToPdf(String excelFilePath, String pdfFilePath) {
        convertExcelToPdf(excelFilePath, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void convertExcelToPdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        InputStream in = null;
        try {
            in = new FileInputStream(excelFilePath);
        } catch (Exception e) {
            log.error("excelFilePath covert inputStream failed", e);
            e.printStackTrace();
        }

        convertExcelToPdfByIn(in, pdfFilePath, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param sourceIn      excel 流
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void convertExcelToPdf(InputStream sourceIn, String pdfFilePath, int[] convertSheets) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        convertExcelToPdfByIn(sourceIn, pdfFilePath, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param sourceIn      excel 流
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    private static void convertExcelToPdfByIn(InputStream sourceIn, String pdfFilePath, int[] convertSheets) {
        //检测与创建目标文件目录
        mkdir(pdfFilePath);

        // 验证 License
        getExcelLicense();

        try (FileOutputStream fileOS = new FileOutputStream(pdfFilePath)) {
            Workbook wb = new Workbook(sourceIn);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);

            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }

            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

        if (null == sheets || sheets.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
            return;
        }

        for (int i = 0; i < sheets.length; i++) {
            wb.getWorksheets().get(i).setVisible(true);
        }

    }

    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getExcelLicense() {
        try (InputStream is = FileConverter.class.getClassLoader().getResourceAsStream("license-file.xml")) {
            com.aspose.cells.License license = new com.aspose.cells.License();
            license.setLicense(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    //+++++++++++++++++++++++++++++【pptToPdf】++++++++++++++++++++++++++++++++++//
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//

    /**
     * ppt 转 pdf
     *
     * @param pptFilePath ppt文件路径
     * @return 返回pdf文件路径
     */
    public static String convertPowerPointToPdf(String pptFilePath) {
        String pdfFilePath = getPdfFilePath(pptFilePath);
        convertPowerPointToPdf(pptFilePath, pdfFilePath);
        return pdfFilePath;
    }


    /**
     * ppt 转 pdf
     *
     * @param pptFilePath ppt文件路径
     * @param pdfFilePath 生成pdf文件路径
     */
    public static void convertPowerPointToPdf(String pptFilePath, String pdfFilePath) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        InputStream in = null;
        try {
            in = new FileInputStream(pptFilePath);
        } catch (Exception e) {
            log.error("pptFilePath covert inputStream failed", e);
            e.printStackTrace();
        }

        convertPowerPointToPdfByIn(in, pdfFilePath);
    }

    /**
     * ppt 转 pdf
     *
     * @param sourceIn    ppt流
     * @param pdfFilePath 生成pdf文件路径
     */
    public static void convertPowerPointToPdf(InputStream sourceIn, String pdfFilePath) {
        if (pdfFilePath == null || pdfFilePath.length() < 1) {
            throw new NullPointerException("pdfFilePath is null");
        }

        convertPowerPointToPdfByIn(sourceIn, pdfFilePath);
    }

    /**
     * ppt 转 pdf
     *
     * @param sourceIn    ppt流
     * @param pdfFilePath 生成pdf文件路径
     */
    private static void convertPowerPointToPdfByIn(InputStream sourceIn, String pdfFilePath) {
        //检测与创建目标文件目录
        mkdir(pdfFilePath);

        // 验证License
        getPowerPointLicense();

        try (FileOutputStream fileOS = new FileOutputStream(pdfFilePath)) {
            Presentation pres = new Presentation(sourceIn);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            log.error("ppt转换失败");
            e.printStackTrace();
        }
    }

    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getPowerPointLicense() {
        try (InputStream is = FileConverter.class.getClassLoader().getResourceAsStream("license-file.xml")) {
            com.aspose.slides.License license = new com.aspose.slides.License();
            license.setLicense(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意

  1. springboot的项目,引入外部的jar时
<dependency>
            <groupId>aspose-cells</groupId>
            <artifactId>aspose</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>aspose-words</groupId>
            <artifactId>aspose</artifactId>
            <version>15.8.0</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/aspose-words-15.8.0.jar</systemPath>
        </dependency>

        <dependency>
            <groupId>aspose-slides</groupId>
            <artifactId>aspose</artifactId>
            <version>19.3</version>
            <scope>system</scope>
            <systemPath>${basedir}/src/main/resources/lib/aspose.slides-19.3.jar</systemPath>
        </dependency>

我把三个外部的jar包放在resources下的lib目录,lib目录是自己创建的

  1. 打包需要注意在maven插件加入
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
    		<!-- 打包时会将本地jar一起打包-->
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration> 
        </plugins>
    </build>
  1. linux、docker部署的项目,导出或者预览,出现【乱码或者小方格】

docker-compose 解决导出字体乱码问题

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表