doc、docx、txt、xls、xlsx、ppt、pptx等文檔轉爲PDF格式,讀取PDF文檔頁數

@RequestMapping(value = "/pageCount", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object pageCount() throws Exception {
		logBefore(logger, "文件頁數");
		Map<String, Object> map = new HashMap<String, Object>();
		//上傳文件,並得出頁數,前臺計算價格並返回
		PageData pd = this.getPageData();
		String wenjian = pd.getString("FILE");//獲取文件
		if(null != wenjian && !"".equals(wenjian)){
			int i = wenjian.lastIndexOf(".");//獲取文件前綴名
			String zpdf = wenjian.substring(0, i)+".pdf"; //拼接要轉的pdf文件
			int time = Word2PDF.convert2PDF(PathUtil.getClasspath()+wenjian, PathUtil.getClasspath()+zpdf);//判斷需要轉化文件的類型(Excel、Word、ppt)
	        if (time == -4) {
	            System.out.println("轉化失敗,未知錯誤...");
				map.put("data", wenjian);
				map.put("code", 300);
				map.put("msg", "文件錯誤或無文件");
	        } else if(time == -3) {//原文件就是PDF文件,無需轉化...
	            int count = Word2PDF.getPdfPage(PathUtil.getClasspath()+zpdf);//無需轉換pdf,直接獲取頁數
	        	map.put("code", 200);
				map.put("msg", "此文件頁數爲:" +count);
				map.put("count", count);
				map.put("data", wenjian);
	        } else if (time == -2) {
	            System.out.println("轉化失敗,文件不存在...");
				map.put("data", wenjian);
				map.put("code", 300);
				map.put("msg", "文件錯誤或無文件");
	        }else if(time == -1){
	            System.out.println("轉化失敗,請重新嘗試...");
				map.put("data", wenjian);
				map.put("code", 300);
				map.put("msg", "文件錯誤或無文件");
	        }else if (time < -4) {
	            System.out.println("轉化失敗,請重新嘗試...");
				map.put("data", wenjian);
				map.put("code", 300);
				map.put("msg", "文件錯誤或無文件");
	        }else {//轉化成功,用時:  " + time + "s...
	            int count = Word2PDF.getPdfPage(PathUtil.getClasspath()+zpdf);
	        	map.put("code", 200);
				map.put("msg", "此文件頁數爲:" +count);
				map.put("count", count);
				map.put("data", zpdf);
	        }
		}else{
			map.put("data", wenjian);
			map.put("code", 300);
			map.put("msg", "文件錯誤或無文件");
		}
		return AppUtil.returnObject(new PageData(), map);
	}

接口名:http://10.10.10.38:8080/dianshang/appshouji/pageCount?FILE=xxxxx.doc

工具類Word2PDF.java

package com.fh.util;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.itextpdf.text.pdf.PdfReader;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/***
 *
 * @author create by 沙漠的波浪
 *
 * @date 2017年2月21日---下午2:29:27
 *
 */
public class Word2PDF {
    private static final int wdFormatPDF = 17;
    private static final int xlTypePDF = 0;
    private static final int ppSaveAsPDF = 32;

    public static void main(String[] args) {

        int time = convert2PDF("C:/Users/Administrator/Desktop/臨時/測試文件/試卷.docx", "C:/Users/Administrator/Desktop/臨時/測試文件/試卷.pdf");
        //int time = convert2PDF("C:/Users/Administrator/Desktop/臨時/測試文件/test.xlsx", "C:/Users/Administrator/Desktop/臨時/測試文件/test.pdf");
        //int time = convert2PDF("C:/Users/Administrator/Desktop/臨時/測試文件/啦啦啦啦.pptx", "C:/Users/Administrator/Desktop/臨時/測試文件/啦啦啦啦.pdf");
        if (time == -4) {
            System.out.println("轉化失敗,未知錯誤...");
        } else if(time == -3) {
            System.out.println("原文件就是PDF文件,無需轉化...");
        } else if (time == -2) {
            System.out.println("轉化失敗,文件不存在...");
        }else if(time == -1){
            System.out.println("轉化失敗,請重新嘗試...");
        }else if (time < -4) {
            System.out.println("轉化失敗,請重新嘗試...");
        }else {
            System.out.println("轉化成功,用時:  " + time + "s...");
        }

    }

    /***
     * 判斷需要轉化文件的類型(Excel、Word、ppt)
     * 
     * @param inputFile
     * @param pdfFile
     */
    public static int convert2PDF(String inputFile, String pdfFile) {
        String kind = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            return -2;//文件不存在
        }
        if (kind.equals("pdf")) {
            return -3;//原文件就是PDF文件
        }
        if (kind.equals("doc")||kind.equals("docx")||kind.equals("txt")) {
            return Word2PDF.word2PDF(inputFile, pdfFile);
        }else if (kind.equals("ppt")||kind.equals("pptx")) {
            return Word2PDF.ppt2PDF(inputFile, pdfFile);
        }else if(kind.equals("xls")||kind.equals("xlsx")){
            return Word2PDF.Ex2PDF(inputFile, pdfFile);
        }else {
            return -4;
        }
    }

    /***
     * 判斷文件類型
     * 
     * @param fileName
     * @return
     */
    public static String getFileSufix(String fileName) {
        int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
    }

    /***
     * 
     * Word轉PDF
     * 
     * @param inputFile
     * @param pdfFile
     * @return
     */

    private static int word2PDF(String inputFile, String pdfFile) {
        System.out.println("Word轉PDF開始啓動...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
        	ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            System.out.println("打開文檔:" + inputFile);
            Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
            System.out.println("轉換文檔到PDF:" + pdfFile);
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF);
            Dispatch.call(doc, "Close", false);
            long end = System.currentTimeMillis();
            System.out.println("轉換完成,用時:" + (end - start) + "ms");
            int time = (int) ((end - start) / 1000);
            return time;
        } catch (Exception e) {
            System.out.println("Word轉PDF出錯:" + e.getMessage());
            return -1;
        } finally {
            if (app != null) {
                app.invoke("Quit", new Variant[] {});
            }
        }
    }

    /***
     * 
     * Excel轉化成PDF
     * 
     * @param inputFile
     * @param pdfFile
     * @return
     */
    private static int Ex2PDF(String inputFile, String pdfFile) {
        System.out.println("Excel轉PDF開始啓動...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            ComThread.InitSTA(true);
            app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", false);
            app.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            System.out.println("打開文檔:" + inputFile);
            Dispatch excel = Dispatch.invoke(excels, "Open", Dispatch.Method, new Object[] { inputFile, new Variant(false), new Variant(false) }, new int[9]).toDispatch();
            //Dispatch excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
            System.out.println("轉換文檔到PDF:" + pdfFile);
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            // 轉換格式
            // 這裏放棄使用SaveAs
            /*
             * Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
             * pdfFile, new Variant(57), new Variant(false), new Variant(57),
             * new Variant(57), new Variant(false), new Variant(true), new
             * Variant(57), new Variant(true), new Variant(true), new
             * Variant(true) },new int[1]);
             */
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    pdfFile, new Variant(xlTypePDF) // 0=標準 (生成的PDF圖片不會變模糊) 1=最小文件
                    // (生成的PDF圖片糊的一塌糊塗)
            }, new int[1]);
            Dispatch.call(excel, "Close", false);
            long end = System.currentTimeMillis();
            System.out.println("轉換完成,用時:" + (end - start) + "ms");
            int time = (int) ((end - start) / 1000);
            //ComThread.Release();
            return time;
        } catch (Exception e) {
            System.out.println("Word轉PDF出錯:" + e.getMessage());
            return -1;
        } finally {
            if (app != null) {
                app.invoke("Quit", new Variant[] {});
            }
        }
    }

    /***
     * ppt轉化成PDF
     * 
     * @param inputFile
     * @param pdfFile
     * @return
     */
    private static int ppt2PDF(String inputFile, String pdfFile) {
        System.out.println("PowerPoint轉PDF開始啓動...");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            ComThread.InitSTA(true);
            app = new ActiveXComponent("PowerPoint.Application");
            //app.setProperty("Visible", false);
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            System.out.println("打開文檔:" + inputFile);
            Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, false, true).toDispatch();
            System.out.println("轉換文檔到PDF:" + pdfFile);
            File tofile = new File(pdfFile);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{pdfFile,new Variant(ppSaveAsPDF)},new int[1]);
            Dispatch.call(ppt, "Close");
            long end = System.currentTimeMillis();
            System.out.println("轉換完成,用時:" + (end - start) + "ms");
            int time = (int) ((end - start) / 1000);
            //ComThread.Release();
            return time;
        } catch (Exception e) {
            System.out.println("PowerPoint轉PDF出錯:" + e.getMessage());
            return -1;
        } finally {
            if (app != null) {
                app.invoke("Quit");
            }
        }
    }
    
    /**
     * 讀取PDF文檔頁數
     * @param filepath
     * @return
     */
    public static int getPdfPage(String filepath){
        int pagecount = 0;
        PdfReader reader;
        try {
            reader = new PdfReader(filepath);
            pagecount= reader.getNumberOfPages();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(pagecount);
        return pagecount;
    }
    
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章