java实现word、excel、ppt文档转为pdf格式,进行预览

文章介绍了如何在实际项目中,使用Aspose库(包括Aspose-Words、Aspose-Slides和Aspose-Cells)通过Maven依赖将Word、Excel和PPT文件转换为PDF格式,以便预览,同时提及了许可证验证和测试示例。
摘要由CSDN通过智能技术生成

1、实际项目中有这样的需求就是,对一些word、excel、ppt文档进行预览,但是这个无法直接预览,这边可以实现这么个思路,就是先将这些文件转换为pdf然后就可以预览了。

2、实现方式是导入maven依赖,实现转换代码。maven依赖jar包在如下链接自取。

链接: https://pan.baidu.com/s/12HN9NgKhq4sxtO8sH69xdA 提取码: r7f5 

3、maven依赖代码

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>18.6</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-words-18.6-jdk16.jar</systemPath>
        </dependency>
        <!-- ppt转pdf -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>15.9.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-slides-15.9.0.jar</systemPath>
        </dependency>
        <!-- excel转pdf -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

        此处注意:因为jar包是外部导入的,所以pom文件里的jar包路径要以系统路径方式编辑,如:

 <systemPath>${project.basedir}/lib/aspose-cells-8.5.2.jar</systemPath>

4、java逻辑代码

package file;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

class FileTransForUtils {

    private static final Logger logger = LoggerFactory.getLogger(FileTransForUtils.class);
    //word转PDF
    public synchronized static boolean word3Pdf(String wordPath, String pdfPath) {
        if (!getLicense("word")) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(pdfPath);  //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordPath);  //Address是将要被转化的word文档

            doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB,

            // XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            os.close();
            logger.info("word共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
    }
    //excel转PDF
    public synchronized static boolean excel3pdf(String excelPath, String pdfPath) {
        if (!getLicense("excel")) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return false;
        }
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(pdfPath);  //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(pdfFile);
            Workbook wb = new Workbook(excelPath);// 原始excel路径
            wb.save(os,com.aspose.cells.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            os.close();
            logger.info("excel共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
    }
    //ppt转PDF
    public synchronized static boolean ppt3pdf(String pptPath, String pdfPath) {
        // 验证License
        if (!getLicense("ppt")) {
            return false;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            File pdfFile = new File(pdfPath);  //新建一个pdf文档
            os = new FileOutputStream(pdfFile);
            Presentation pres = new Presentation(pptPath);//输入ppt路径
            //IFontsManager fontsManager = pres.getFontsManager();
            pres.save(os,com.aspose.slides.SaveFormat.Pdf);
            long now = System.currentTimeMillis();
            logger.info("ppt共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //剔除水印
    private static boolean getLicense(String type) {
        boolean result = false;
        try {
            // 凭证
            String license =
                    "<License>\n" +
                            "  <Data>\n" +
                            "    <Products>\n" +
                            "      <Product>Aspose.Total for Java</Product>\n" +
                            "      <Product>Aspose.Words for Java</Product>\n" +
                            "    </Products>\n" +
                            "    <EditionType>Enterprise</EditionType>\n" +
                            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
                            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                            "  </Data>\n" +
                            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                            "</License>";
            InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
            if(type.equals("word")){
                License asposeLic = new License();
                asposeLic.setLicense(is);
            }else if (type.equals("excel")){
                com.aspose.cells.License asposeLic = new com.aspose.cells.License();
                asposeLic.setLicense(is);
            }else if (type.equals("ppt")){
                com.aspose.slides.License aposeLic = new com.aspose.slides.License();
                aposeLic.setLicense(is);
            }
            result = true;
        } catch (Exception e) {
            logger.error(String.valueOf(e));
            e.printStackTrace();
            return false;
        }
        return result;
    }
    /**
     * 判断资源类型文档类
     */
    private static String getResourceTypesDocument(String suffix) {
        String type = null;
        switch (suffix) {
            //文档类型
            case ".doc":
            case ".docx":
            case ".txt":
                type = "word";
                break;
            case ".xls":
            case ".xlsx":
                type = "excel";
                break;
            case ".ppt":
            case ".pptx":
                type = "ppt";
                break;
        }
        return type;
    }

    public static void main(String[] args) {
        String inputPath = "E:/test/测试.xlsx";
        String outputPath = "E:/test/11.pdf";
        String suffix = inputPath.substring(inputPath.lastIndexOf("."));
        String type = getResourceTypesDocument(suffix);
        if("word".equals(type)){
            word3Pdf(inputPath,outputPath);
        }else if("excel".equals(type)){
            excel3pdf(inputPath,outputPath);
        }else if("ppt".equals(type)){
            ppt3pdf(inputPath,outputPath);
        }
    }
}

5、测试运行,便可以正常的将word、excel、ppt转换为pdf文件了。

好的,以下是一个Java获取各种文档页数的工具类,使用了Apache POI和Apache PDFBox库: ``` import java.io.File; import java.io.FileInputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.poi.sl.usermodel.SlideShow; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.xslf.usermodel.XMLSlideShow; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.pdfbox.pdmodel.PDDocument; public class DocumentPageCount { public static int getExcelPageCount(String filePath) { try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); Workbook workbook = null; if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(fis); } else if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(fis); } fis.close(); return workbook.getNumberOfSheets(); } catch (Exception e) { e.printStackTrace(); return 0; } } public static int getPptPageCount(String filePath) { try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); SlideShow slideshow = null; if (filePath.endsWith(".ppt")) { slideshow = new HSLFSlideShow(fis); } else if (filePath.endsWith(".pptx")) { slideshow = new XMLSlideShow(fis); } fis.close(); return slideshow.getSlides().size(); } catch (Exception e) { e.printStackTrace(); return 0; } } public static int getWordPageCount(String filePath) { try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); HWPFDocument doc = null; Range range = null; XWPFDocument docx = null; if (filePath.endsWith(".doc")) { doc = new HWPFDocument(fis); range = doc.getRange(); } else if (filePath.endsWith(".docx")) { docx = new XWPFDocument(fis); range = docx.getDocument().getBody().getDocumentContent().getEndOfContent().getRange(); } fis.close(); return range.numParagraphs(); } catch (Exception e) { e.printStackTrace(); return 0; } } public static int getPdfPageCount(String filePath) { try { File file = new File(filePath); PDDocument document = PDDocument.load(file); int pageCount = document.getNumberOfPages(); document.close(); return pageCount; } catch (Exception e) { e.printStackTrace(); return 0; } } } ``` 这个工具类包含了四个方法,分别用于获取ExcelPPTWordPDF文档的页数。您可以在自己的项目中使用这些方法来获取文档的页数。例如,要获取一个Excel文件的页数,可以调用`DocumentPageCount.getExcelPageCount("path/to/excel/file.xls")`。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值