java语言Word、excel、ppt转pdf

  1. 引入依赖
    具体
<dependency>

<groupId>net.sf.jacob-project</groupId>

<artifactId>jacob</artifactId>

<version>1.14.3</version>

</dependency>

如果不能够自动引入,需要手动下载(可以直接百度进行下载),将下载好的jar包存放在项目resource中,修改pom文件如下:

<dependency>
    <groupId>net.sf.jacob-project</groupId>
    <artifactId>jacob</artifactId>
    <version>1.17</version>
    <scope>system</scope>
    <systemPath>${basedir}/src/main/resources/lib/jacob.jar</systemPath>
</dependency>
  1. Word转PDF工具类

public class WordUtils {

//    public static void main(String[] args) throws IOException {
//
//        String source3 = "C:\\Users\\楚\\Desktop\\能源管理系统上线试运行方案.doc";
//        String target3 = "C:\\Users\\楚\\Desktop\\能源管理系统上线试运行方案.pdf";
//        WordUtils pdf = new WordUtils();
//        pdf.word2pdf(source3, target3);
//    }

    public static void word2pdf( String wordFile, String pdfFile) {
        // 开始时间
        long start = System.currentTimeMillis();
        ComThread.InitSTA(true);
        // 打开word
        ActiveXComponent app = new ActiveXComponent("Word.Application");
        app.setProperty("Visible", new Variant(false));
        app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
        System.out.println("开始转换...");

        try {
            // 设置word不可见,很多博客下面这里都写了这一句话,其实是没有必要的,因为默认就是不可见的,如果设置可见就是会打开一个word文档,对于转化为pdf明显是没有必要的
            //app.setProperty("Visible", false);
            // 获得word中所有打开的文档
            Dispatch documents = app.getProperty("Documents").toDispatch();
            System.out.println("打开文件: " + wordFile);
            // 打开文档
            Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
            // 如果文件存在的话,不会覆盖,会直接报错,所以我们需要判断文件是否存在
            File target = new File(pdfFile);
            if (target.exists()) {
                target.delete();
            }
            System.out.println("另存为: " + pdfFile);
            // 另存为,将文档保存为pdf,其中word保存为pdf的格式宏的值是17
            Dispatch.call(document, "SaveAs", pdfFile, 17);
            // 关闭文档
            Dispatch.call(document, "Close", false);


            // 结束时间
            long end = System.currentTimeMillis();
            System.out.println("转换成功,用时:" + (end - start) + "ms");
     
        }catch(Exception e) {

            e.getMessage();
            System.out.println("转换失败"+e.getMessage());
        
        }finally {
            // 关闭office
            app.invoke("Quit", 0);
            ComThread.Release();
            ComThread.quitMainSTA();
        }
    }

}

  1. Excel转PDF工具类
public class ExcelToPDFUtil {

//    public static void main(String[] args) {
//        int time = Ex2PDF("C:\\Users\\楚\\Desktop\\16318606956952405cba5-7峰谷能耗分析.xlsx", "C:\\Users\\楚\\Desktop\\峰谷能耗分析.pdf");
//        System.out.println(time);
//    }

    public static void Ex2PDF(String inputFile, String pdfFile) {
        // 0=标准 (生成的PDF图片不会变模糊) 1=最小文件(生成的PDF图片糊的一塌糊涂)
        final int xlTypePDF = 0;
        // try {
        // User32.SetWinEventHook(new UINT(0x0003), new UINT(0x0003), 0, 0, new DWORD(0), new DWORD(0), new UINT(0));
        // } catch (IllegalAccessException e1) {
        // e1.printStackTrace();
        // } catch (NativeException e1) {
        // e1.printStackTrace();
        // }
        ComThread.InitSTA(true);
        ActiveXComponent ax = new ActiveXComponent("Excel.Application");
        long date = new Date().getTime();
        ax.setProperty("Visible", new Variant(false));
        ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
        try {
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[]{inputFile, new Variant(false), new Variant(false)},
                    new int[9]).toDispatch();
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[]{
                    new Variant(0), // PDF格式=0
                    pdfFile, new Variant(xlTypePDF), Variant.VT_MISSING, Variant.VT_MISSING, Variant.VT_MISSING, Variant.VT_MISSING,
                    new Variant(false), Variant.VT_MISSING}, new int[1]);
            long date2 = new Date().getTime();
            int time = (int) ((date2 - date) / 1000);
            Dispatch.call(excel, "Close", new Variant(false));
          
        } catch (Exception e) {
          
        
            e.printStackTrace();
          
        } finally {
            ax.invoke("Quit");
            ax = null;
            ComThread.Release();
            ComThread.quitMainSTA();
        }
    }


}

  1. ppt转PDF工具类
public class PoiUtils {
    static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。

    static final int ppSaveAsPDF = 32;// ppt 转PDF 格式
//    public static void main(String[] args) throws IOException {
//
//        String source3 = "C:\\Users\\Ray\\Desktop\\eam\\企业资产管理-EAM系统介绍.pptx";
//        String target3 = "C:\\Users\\Ray\\Desktop\\eam\\企业资产管理-EAM系统介绍2020.pdf";
//        PoiUtils pdf = new PoiUtils();
//        pdf.ppt2pdf(source3, target3);
//    }

    //PPT文档转PDF

    public static void ppt2pdf( String source, String target) {
        System.out.println("启动PPT");
        long start = System.currentTimeMillis();
        ComThread.InitSTA(true);
        ActiveXComponent app = new ActiveXComponent("Powerpoint.Application"); //创建office的一个应用,比如你操作的是word还是ppt等
//        app.setProperty("Visible", new Variant(false));
//        app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
        try {

            //Dispatch 调度处理类,封装了一些操作来操作office
            Dispatch presentations = app.getProperty("Presentations").toDispatch();
            System.out.println("打开文档" + source);
            Dispatch presentation = Dispatch.call(presentations, "Open",
                    source,// FileName
                    true,// ReadOnly
                    true,// Untitled 指定文件是否有标题。
                    false // WithWindow 指定文件是否可见。
            ).toDispatch();

            System.out.println("转换文档到PDF " + target);
            File tofile = new File(target);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(presentation,//
                    "SaveAs", //
                    target, // FileName
                    ppSaveAsPDF);

            Dispatch.call(presentation, "Close");


            long end = System.currentTimeMillis();
            System.out.println("转换完成."+source+".用时:" + (end - start) + "ms.");
           
        } catch (Exception e) {
           
            System.out.println("========Error:文档转换失败:" + e.getMessage());
        } finally {
            if (app != null)
                app.invoke("Quit");


            ComThread.Release();
            ComThread.quitMainSTA();
        }
    }
}

使用时直接调用即可,两个参数分别是源文件的绝对地址(包括文件名)和转换后的文件绝对地址(包括文件名)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,以下是一个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")`。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值