Word(doc、docx)、Excel(xls/xlsx)、PPT(ppt/pptx)转PDF格式文件

目录

一.需要使用的jar包依赖

二.代码

Word转PDF操作

excel转pdf

图片转pdf

ppt转换Pdf

pptx转Pdf

测试


一.需要使用的jar包依赖

<!-- 转换工具 -->
        <!-- aspose-cells -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>
        <!-- aspose-words -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>20.12</version>
        </dependency>

        <!-- itext转换pdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <!-- Apache POI -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- Apache POI - HSLF (提供PPT操作功能) -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <!-- Apache POI - HSLF (提供PPT读取功能) -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>

excel-license.xml 

 

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

注意: "aspose-cells"需要配合上面的excel-license.xml文件一起使用

excel-license.xml放在代码所在模块下的资源目录下

aspose-cells 和 aspose-words 如果maven找不到,可以选择手动导入jar包

具体方法可以参考我的这篇文章: http://t.csdn.cn/kwUAR

jar包链接: 

链接:https://pan.baidu.com/s/1aeFHEj_v4ZF9ByY2093rBw 
提取码:as1b

本次使用的版本是

二.代码

1.准备工具类

/**
 * pdf工具类
 */
public class PdfUtils {
    ....
}

2.默认pdf存放路径方法

/**
     * 获取pdf存放路径 默认存放在源文件路径下
     * @param sourceFile 源文件绝对路径
     * @return pdfPath
     */
    public static String getPdfFilePath(String sourceFile){
        File file = new File(sourceFile);
        if(!file.exists()) throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);
        // 获取文件后缀
        String suffix = FileUploadUtils.getExtension(file);
        return sourceFile.replaceAll(suffix,"pdf");
    }

Word转PDF操作

/**
     * Word转PDF操作
     *
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void wordToPdf(String sourceFile, String targetFile) {
        try {
            long old = System.currentTimeMillis();
            targetFile = StringUtils.isEmpty(targetFile) ? getPdfFilePath(sourceFile) : targetFile;
            File file = new File(targetFile);  //新建一个空白pdf文档
            FileOutputStream os = new FileOutputStream(file);
            com.aspose.words.Document doc = new com.aspose.words.Document(sourceFile); //sourceFile是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            os.close();
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new CustomException(CustomExceptionEnums.FILES_CONVERT_ERROR);
        }
    }

excel转pdf

/**
     * excel 转 pdf
     *
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void excelToPdf(String sourceFile, String targetFile) {
        excelToPdf(sourceFile, targetFile, null);
    }



/**
     * 隐藏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);
        } else {
            for (int i = 0; i < sheets.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }





/**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excelToPdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        try {
            pdfFilePath = StringUtils.isEmpty(pdfFilePath) ? PdfUtils.getPdfFilePath(excelFilePath) : pdfFilePath;
            // 验证 License
            getLicense();
            Workbook wb = new Workbook(excelFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFilePath);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new CustomException(CustomExceptionEnums.FILES_CONVERT_ERROR);
        }
    }

图片转pdf

/**
     * 图片 转 pdf
     *
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void imageToPdf(String sourceFile, String targetFile) {
        try {
            targetFile = StringUtils.isEmpty(targetFile) ? getPdfFilePath(sourceFile) : targetFile;
            BufferedImage img = ImageIO.read(new File(sourceFile));
            FileOutputStream fos = new FileOutputStream(targetFile);
            Document doc = new Document(PageSize.A3, 20, 20, 20, 20);
            doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
            Image image = Image.getInstance(sourceFile);
            PdfWriter.getInstance(doc, fos);
            doc.open();
            doc.add(image);
            doc.close();
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new CustomException(CustomExceptionEnums.FILES_CONVERT_ERROR);
        }
    }

ppt转换Pdf

/**
     * ppt转换Pdf
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void pptToPdf(String sourceFile, String targetFile) {

        File sourceFileByPath = new File(sourceFile);
        if(!sourceFileByPath.exists()) throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);
        targetFile = StringUtils.isEmpty(targetFile) ? getPdfFilePath(sourceFile) : targetFile;
        File targetFileByPath = new File(targetFile);

        Document document = null;
        HSLFSlideShow hslfSlideShow = null;
        PdfWriter pdfWriter = null;

        try {
            hslfSlideShow = new HSLFSlideShow(Files.newInputStream(sourceFileByPath.toPath()));

            // 获取ppt文件页面
            Dimension dimension = hslfSlideShow.getPageSize();

            document = new Document();

            // pdfWriter实例
            pdfWriter = PdfWriter.getInstance(document, Files.newOutputStream(targetFileByPath.toPath()));

            document.open();

            PdfPTable pdfPTable = new PdfPTable(1);

//            List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();
            java.util.List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();

            for (int i=0; i < hslfSlideList.size(); i++) {
                HSLFSlide hslfSlide = hslfSlideList.get(i);
                // 设置字体, 解决中文乱码
                for (HSLFShape shape : hslfSlide.getShapes()) {
                    if (shape instanceof HSLFTextShape) {
                        HSLFTextShape textShape = (HSLFTextShape) shape;
                        for (HSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                            for (HSLFTextRun textRun : textParagraph.getTextRuns()) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);

                Graphics2D graphics2d = bufferedImage.createGraphics();

                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));

                hslfSlide.draw(graphics2d);

                graphics2d.dispose();

                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);

                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);

            }
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new CustomException(CustomExceptionEnums.FILES_CONVERT_ERROR);
        } finally {
            if (document != null) {
                document.close();
            }
            if (pdfWriter != null) {
                pdfWriter.close();
            }
        }
        System.out.println("convert success");
    }

pptx转Pdf

/**
     * pptx转Pdf
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void pptxToPdf(String sourceFile, String targetFile) {

        File sourceFileByPath = new File(sourceFile);
        if(!sourceFileByPath.exists()) throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);
        targetFile = StringUtils.isEmpty(targetFile) ? getPdfFilePath(sourceFile) : targetFile;
        File targetFileByPath = new File(targetFile);

        Document document = null;

        XMLSlideShow slideShow = null;

        PdfWriter pdfWriter = null;

        try {

            slideShow = new XMLSlideShow(Files.newInputStream(sourceFileByPath.toPath()));

            Dimension dimension = slideShow.getPageSize();

            document = new Document();

            pdfWriter = PdfWriter.getInstance(document, Files.newOutputStream(targetFileByPath.toPath()));

            document.open();

            PdfPTable pdfPTable = new PdfPTable(1);

            java.util.List<XSLFSlide> slideList = slideShow.getSlides();
//            List<XSLFSlide> slideList = (List<XSLFSlide>) slides;

            for (int i = 0, row = slideList.size(); i < row; i++) {

                XSLFSlide slide = slideList.get(i);

                // 设置字体, 解决中文乱码
                for (XSLFShape shape : slide.getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape textShape = (XSLFTextShape) shape;

                        for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                            for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }

                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);

                Graphics2D graphics2d = bufferedImage.createGraphics();

                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new java.awt.Font("宋体", java.awt.Font.PLAIN, 12));

                slide.draw(graphics2d);

                graphics2d.dispose();

                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);

                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
            throw new CustomException(CustomExceptionEnums.FILES_CONVERT_ERROR);
        } finally {
            if (document != null) {
                document.close();
            }
            if (pdfWriter != null) {
                pdfWriter.close();
            }
        }
        System.out.println("convert success");
    }

测试

/**
     * 根据文件类型转换pdf
     * @param sourceFile 源文件
     * @param targetFile  目标文件
     */
    public static void convertToPdf(String sourceFile, String targetFile){
        File file = new File(sourceFile);
        if(!file.exists()) throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);

        String fileName = file.getName();
        // 获取文件后缀名
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(StringUtils.isNotEmpty(suffix)){

            if(FileUploadUtils.isAllowedExtension(suffix, MimeTypeUtils.DEFAULT_EXCEL_EXTENSION)){
                // excel
                excelToPdf(sourceFile, targetFile);
            }
            if(FileUploadUtils.isAllowedExtension(suffix, MimeTypeUtils.DEFAULT_WORD_EXTENSION)){
                // word
                wordToPdf(sourceFile, targetFile);
            }
            if(FileUploadUtils.isAllowedExtension(suffix, MimeTypeUtils.DEFAULT_IMAGE_EXTENSION)){
                // image
                imageToPdf(sourceFile, targetFile);
            }
            if(FileUploadUtils.isAllowedExtension(suffix, MimeTypeUtils.DEFAULT_PPT_EXTENSION)){
                if(suffix.equalsIgnoreCase("ppt"))pptToPdf(sourceFile, targetFile);// ppt
                if(suffix.equalsIgnoreCase("pptx"))pptxToPdf(sourceFile, targetFile);// pptx
            }

        }else {
            throw new CustomException(CustomExceptionEnums.UNSUPPORTED_FILE_TYPE);
        }


    }

MimeTypeUtils
/**
 * 媒体类型工具类
 * 
 */
public class MimeTypeUtils
{
/** 默认支持的图片格式 */
    public static final String[] DEFAULT_IMAGE_EXTENSION = {
            "bmp", "gif", "jpg", "jpeg", "png"
    };


    /** 默认支持的word文件格式 */
    public static final String[] DEFAULT_WORD_EXTENSION = {
            "doc", "docx"
    };

    /** 默认支持的excel文件格式 */
    public static final String[] DEFAULT_EXCEL_EXTENSION = {
            "xls", "xlsx"
    };

    /** 默认支持的ppt文件格式 */
    public static final String[] DEFAULT_PPT_EXTENSION = {
            "ppt", "pptx"
    };

}

就是执行速度上有点儿慢,慢点儿或者文件大点儿要2s多甚至更久

如果大家有更好的方案或者建议欢迎指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值